快速入门
本指南通过一个简单可用的示例,帮助您开始在 Node 中使用 gRPC。
快速入门
本指南通过一个简单可用的示例,帮助您开始在 Node 中使用 gRPC。
先决条件
- Node 版本 8.13.0 或更高
下载示例
您需要一份示例代码的本地副本才能完成本快速入门。从我们的 GitHub 仓库下载示例代码(以下命令会克隆整个仓库,但您只需本快速入门和其他教程所需的示例即可)
# Clone the repository to get the example code
git clone -b @grpc/grpc-js@1.9.0 --depth 1 --shallow-submodules https://github.com/grpc/grpc-node
# Navigate to the node example
cd grpc-node/examples
# Install the example's dependencies
npm install
# Navigate to the dynamic codegen "hello, world" Node example:
cd helloworld/dynamic_codegen
运行 gRPC 应用
在 examples/helloworld/dynamic_codegen
目录中
运行服务器
node greeter_server.js
在另一个终端中,运行客户端
node greeter_client.js
恭喜!您刚刚运行了一个使用 gRPC 的客户端-服务器应用。
更新 gRPC 服务
现在我们来看看如何更新应用,以便在服务器上增加一个供客户端调用的方法。我们的 gRPC 服务使用 protocol buffers 定义;您可以在基础教程中了解更多关于如何在 .proto
文件中定义服务的信息。目前您只需知道,服务器和客户端“stub”都有一个 SayHello
RPC 方法,它接收客户端的 HelloRequest
参数并返回服务器的 HelloReply
,这个方法定义如下
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
我们来更新它,让 Greeter
服务有两个方法。编辑 examples/protos/helloworld.proto
,并添加一个新的 SayHelloAgain
方法,使用相同的请求和响应类型
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
记得保存文件!
更新并运行应用
现在我们有了新的服务定义,但仍需要在示例应用的手动编写的部分实现并调用新方法。
更新服务器
在同一目录中,打开 greeter_server.js
。按如下方式实现新方法
function sayHello(call, callback) {
callback(null, {message: 'Hello ' + call.request.name});
}
function sayHelloAgain(call, callback) {
callback(null, {message: 'Hello again, ' + call.request.name});
}
function main() {
var server = new grpc.Server();
server.addService(hello_proto.Greeter.service,
{sayHello: sayHello, sayHelloAgain: sayHelloAgain});
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
server.start();
});
}
更新客户端
在同一目录中,打开 greeter_client.js
。按如下方式调用新方法
function main() {
var client = new hello_proto.Greeter('localhost:50051',
grpc.credentials.createInsecure());
client.sayHello({name: 'you'}, function(err, response) {
console.log('Greeting:', response.message);
});
client.sayHelloAgain({name: 'you'}, function(err, response) {
console.log('Greeting:', response.message);
});
}
运行!
就像之前一样,在 examples/helloworld/dynamic_codegen
目录中
运行服务器
node greeter_server.js
在另一个终端中,运行客户端
node greeter_client.js
接下来
最后修改于 2024 年 11 月 25 日:feat: move the $ shell line indicator to scss (#1354) (ab8b3af)