nodejs搭建grpc

2023-05-25 grpc 搭建 Nodejs

前言

gRPC 是谷歌开源的高性能跨语言 RPC 框架,它的目标是让客户端应用像调用本地函数一样调用服务器端的方法,支持多种编程语言,包括:C++、Python、Java、Go、Node.js 等语言。

在 Node.js 中使用 gRPC 可以极大地方便我们进行服务端和客户端的交互,并且在保证高性能的同时,也可以提供数据安全和保密性,本文将介绍如何使用 Node.js 搭建 gRPC 服务端和客户端。

第一步:安装 Node.js 和 gRPC

首先,需要确保本地已经安装了 Node.js 和 npm。然后,在终端输入以下命令安装 gRPC:

安装完成后,你可以在 package.json 文件中看到 gRPC 的版本信息。

image-20210819120809541

第二步:定义.proto文件

gRPC 通过 proto-file 定义服务,该文件用于定义服务的接口、消息格式等等。下面我们先定义一个简单的服务,让客户端向服务端发送一个消息,收到消息后返回一个已修改的消息。创建一个名为 example.proto 的文件,定义以下内容:

syntax = "proto3";

package example;

service Example {
  rpc ModifyMessage (Message) returns (Message){}

}
message Message {
  string content = 1;
}

这里使用了 grpc_tools_node_protoc 生成 Node.js 所需的代码,并指定了输出目录。

生成的代码包括:example_pb.js 和 example_grpc_pb.js。

第四步:实现服务端

服务器端代码如下:

const grpc = require("grpc");
const example = require("./example_pb");
const exampleService = require("./example_grpc_pb");

const server = new grpc.Server();

function modifyMessage(call, callback) {
  const response = new example.Message();
  response.setContent(call.request.getContent().toUpperCase());
  callback(null, response);
}

server.addService(exampleService.ExampleService, {
  modifyMessage: modifyMessage,
});

server.bind("localhost:50051", grpc.ServerCredentials.createInsecure());
console.log("Server running at http://localhost:50051");
server.start();

在这个例子中,服务端新建了一个 grpc 服务器,并在该服务器上添加了一个名为 modifyMessage 的方法。该方法接收一个 Message 对象作为参数,将 Message 对象中的 content 字段转换为大写并返回。

最后,我们使用 bind() 方法将服务绑定到 localhost:50051,并启动服务器。

第五步:实现客户端

客户端代码如下:

const grpc = require("grpc");
const example = require("./example_pb");
const exampleService = require("./example_grpc_pb");

const client = new exampleService.ExampleClient(
  "localhost:50051",
  grpc.credentials.createInsecure()
);

const request = new example.Message();

request.setContent("Hello World!");

client.modifyMessage(request, function (err, response) {
  console.log("Modified message: ", response.getContent());
});

至此,我们已经成功地实现了一个基础的 gRPC 服务端和客户端的交互过程。

总结

本文介绍了如何使用 Node.js 搭建 gRPC 服务端和客户端,并在创建服务和建立连接之间使用 protobuf 定义了数据结构和消息格式。gRPC 是一个功能强大的跨语言 RPC 框架,对于需要在客户端和服务端之间快速传输数据的应用非常有用。

相关文章