网站建设工作 方案/环球贸易网
RPC
- RPC(Remote Procedure Call Protocol),是远程过程调用的缩写
- 通俗的说就是调用远处的一个函数,与之相对应的是本地函数调用
- 本地函数调用:参数,返回值,代码段都在本地的一个进程空间内
- 远程函数调用:远程,即跨进程,这个进程部署在另一台服务器上,也就是调用另一台服务器上的函数
- 远程函数调用是rpc主要实现的功能,也是微服务的的主要功能
- 所谓微服务的实现,通俗而言,就是让我们可以像调用本地函数一样调用远程函数
- 注意
- RPC并不是一种具体的技术框架,而是一种技术思想
- 广义上讲,任何通过网络,远程调用另一个进程中的方法的技术,都可以称为RPC
- 随着时代的发展,越来越多优秀的RPC微服务框架进入我们的视野
- 比如谷歌的GRPC框架、阿里的dubbo框架、Facebook的Thrift、腾讯的Tars等
- 我们主要关注GRPC框架实现nodejs微服务
GRPC

- gRPC 官方文档中文版:http://doc.oschina.net/grpc
- gRPC官网:https://grpc.io/
- gRPC 是一个高性能、开源和通用的 RPC 框架,面向移动端和 HTTP/2 设计
- 目前提供 C、Java 和 Go语言版本,分别是:grpc, grpc-java, grpc-go
- 其中 C版本支持 C, C++, Node.js, Python, Ruby, Objective-C, PHP和C#
- 特点
- 1、提供几乎所有主流语言的实现,打破语言隔阂
- 2、基于 HTTP/2 标准设计,带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等待
- 3、默认使用Protocol Buffers序列化,性能相较于RESTful Json好很多
- 4、工具链成熟,代码生成便捷,开箱即用
- 5、支持双向流式的请求和响应,对批量处理、低延时场景友好
- 总结
- 这些特性使得其在移动设备上表现更好,更省电和节省空间占用
- 有了GRPC,我们可以一次性的在一个.proto文件中定义服务
- 并使用任何支持它的语言去实现客户端和服务端
- GRPC默认使用protocol buffers
- 它是google开源的一套成熟的结构数据序列化机制(当然也可以使用其他数据格式如JSON)
- 可以用proto files创建gRPC服务
- 用protocol buffers消息类型来定义方法参数和返回类型
- 在GRPC客户端可以直接调用不同服务器上的远程程序,就像调用本地程序一样, 很容易构建分布式应用和服务
- 和很多RPC系统一样,服务负责实现定义好的接口并处理客户端请求
- 客户端根据接口描述直接调用需要的服务, 客户端和服务器可以分别使用gRPC支持的不同语言实现
官方example解析
- 文档:https://grpc.io/docs/languages/node/quickstart/
1 )下载示例体验
# Clone the repository to get the example code
$ git clone -b v1.53.0 --depth 1 --shallow-submodules https://github.com/grpc/grpc
# Navigate to the node example
$ cd grpc/examples/node
# Install the example's dependencies
$ npm install
# Navigate to the dynamic codegen "hello, world" Node example:
$ cd dynamic_codegen
2 )运行示例程序
2.1 先启动服务端
$ node greeter_server.js
2.2 后启动客户端
$ node greeter_client.js
- 会直接返回 Hello world
3 ) gRPC代码解析
-
在上述 dynamic_codegen 目录中的代码就是微服务的代码
-
3.1 greeter_server.js
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */var PROTO_PATH = __dirname + '/../../protos/helloworld.proto';// 1. 引入工具文件 var grpc = require('@grpc/grpc-js'); var protoLoader = require('@grpc/proto-loader'); // 2. 加载proto文件 var packageDefinition = protoLoader.loadSync(PROTO_PATH,{keepCase: true,longs: String,enums: String,defaults: true,oneofs: true}); // 固定写法 var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld; // 注意这里的 helloworld 是包名// 3. 定义远程调用方法: 名称,入参,返参,需要按照proto的约束来 /*** Implements the SayHello RPC method.*/ function sayHello(call, callback) {callback(null, {message: 'Hello ' + call.request.name}); }// 4. 启动微服务 /*** Starts an RPC server that receives requests for the Greeter service at the* sample server port*/ function main() {var server = new grpc.Server(); // 4.1 创建 server 实例server.addService(hello_proto.Greeter.service, {sayHello: sayHello}); // 4.2 增加 服务, 第二个参数是绑定远程调用方法// 4.3 绑定端口 createInsecure 可以理解为通信的协议凭证server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {server.start();}); }main();
-
3.2 greeter_client.js
/*** Copyright 2015 gRPC authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/var PROTO_PATH = __dirname + '/../../protos/helloworld.proto';// 1. 引入工具文件var parseArgs = require('minimist');var grpc = require('@grpc/grpc-js');var protoLoader = require('@grpc/proto-loader');// 2. 加载proto文件var packageDefinition = protoLoader.loadSync(PROTO_PATH,{keepCase: true,longs: String,enums: String,defaults: true,oneofs: true});// 固定写法var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld; // 注意这里的 helloworld 是包名function main() {// 获取客户端传入参数var argv = parseArgs(process.argv.slice(2), {string: 'target'});// 处理 target参数var target;if (argv.target) {target = argv.target;} else {target = 'localhost:50051';}// 这里创建 Greeter 服务实例, 这里target是远程服务var client = new hello_proto.Greeter(target, grpc.credentials.createInsecure());// 这里是返回的名称处理var user;if (argv._.length > 0) {user = argv._[0]; } else {user = 'world';}// 客户端调用远程sayHello,传入name参数,并在回调中拿到服务端返回数据client.sayHello({name: user}, function(err, response) {console.log('Greeting:', response.message);});}main();
-
上述服务端和客户端中均引入了 helloworld.proto 这个文件有特定的书写语法
// 这里是定义版本 syntax = "proto3";// 以下java相关配置可以删除 option java_multiple_files = true; option java_package = "io.grpc.examples.helloworld"; option java_outer_classname = "HelloWorldProto"; option objc_class_prefix = "HLW";// 这里是定义包名 package helloworld;// 这里是定义服务 对应生成接口 service Greeter {// Sends a greeting// 这里要求微服务中必须实现 SayHello 方法,在此方法中接收一个参数叫 HelloRequest,返回是 HelloReply// 可见对方法名,接收和返回都进行了约束rpc SayHello (HelloRequest) returns (HelloReply) {}rpc SayHelloStreamReply (HelloRequest) returns (stream HelloReply) {} }// The request message containing the user's name. // HelloRequest 是一个 message 对应js中的一个对象 message HelloRequest {string name = 1; }// The response message containing the greetings message HelloReply {string message = 1; }
-
还有两个工具: grpc、protoLoader
var grpc = require('@grpc/grpc-js'); // 这里提供 grpc 服务 var protoLoader = require('@grpc/proto-loader'); // 这里是 proto文件 加载器
-
有上述服务端代码中,我们看到有几个必要的步骤
- 1 ) 引入工具
- 2 ) 加载proto文件 (服务端和客户端对应的都是一个proto文件,需要注意的是,实际上client和server可能在不同服务器上)
- 3 ) 定义远程调用方法
- 注意:外部proto文件中是 SayHello, 定义远程调用方法时写的是 sayHello
- 是因为protoLoader.loadSync 方法中的配置 keepCase
- 还是统一起来比较好
- 4 ) 启动微服务
- 创建 server 实例
- 增加 服务, 第二个参数是绑定远程调用方法
- 绑定端口 createInsecure 可以理解为通信的协议凭证
-
客户端代码中,注意事项同上并参考注释
-
后面自己要写的时候,可以将上述客户端和服务端,以及proto文件拷贝出去,写自己的业务需求