推荐答案
// www.javascriptcn.com code example
// 1. 安装 gRPC 依赖
npm install @grpc/grpc-js @grpc/proto-loader
// 2. 定义 proto 文件
// example.proto
syntax = "proto3";
package example;
service ExampleService {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
// 3. 创建 gRPC 服务器
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync('example.proto', {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const exampleProto = grpc.loadPackageDefinition(packageDefinition).example;
function sayHello(call, callback) {
callback(null, { message: `Hello, ${call.request.name}` });
}
const server = new grpc.Server();
server.addService(exampleProto.ExampleService.service, { sayHello });
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
server.start();
console.log('gRPC server running at http://0.0.0.0:50051');
});
// 4. 创建 gRPC 客户端
const client = new exampleProto.ExampleService('localhost:50051', grpc.credentials.createInsecure());
client.sayHello({ name: 'World' }, (err, response) => {
if (err) {
console.error(err);
} else {
console.log(response.message); // 输出: Hello, World
}
});本题详细解读
1. 什么是 gRPC?
gRPC 是一个高性能、开源的通用 RPC 框架,由 Google 开发。它基于 HTTP/2 协议,使用 Protocol Buffers 作为接口定义语言(IDL),支持多种编程语言。
2. 如何使用 gRPC 实现 RPC?
- 定义服务接口:使用
.proto文件定义服务接口和消息格式。 - 生成代码:使用
protoc编译器生成客户端和服务端代码。 - 实现服务端:在服务端实现定义的服务接口。
- 实现客户端:在客户端调用远程服务。
3. 代码解析
- 安装依赖:
@grpc/grpc-js是 gRPC 的 Node.js 实现,@grpc/proto-loader用于加载.proto文件。 - 定义 proto 文件:
example.proto文件定义了服务接口ExampleService和消息格式HelloRequest和HelloResponse。 - 创建 gRPC 服务器:使用
grpc.Server创建服务器,并实现sayHello方法。 - 创建 gRPC 客户端:使用生成的客户端代码调用远程服务。
4. 运行流程
- 服务器启动后监听
50051端口。 - 客户端通过
localhost:50051连接到服务器,并调用sayHello方法。 - 服务器接收到请求后,返回
Hello, World消息。