快速入门
本指南通过一个简单的运行示例帮助您开始使用 Ruby 中的 gRPC。
快速入门
前提条件
- Ruby 版本 2 或更高
gRPC
要安装 gRPC,请运行以下命令
gem install grpc
gRPC 工具
Ruby 的 gRPC 工具包括协议缓冲区编译器 protoc
以及用于从 .proto
服务定义生成服务器和客户端代码的专用插件。对于快速入门示例的第一部分,我们已经从 helloworld.proto 生成了服务器和客户端存根,但在快速入门的其余部分以及后续教程和您自己的项目中,您将需要这些工具。
要安装 gRPC 工具,请运行以下命令
gem install grpc-tools
下载示例
您需要一份示例代码的本地副本才能完成本快速入门。从我们的 GitHub 仓库下载示例代码(以下命令将克隆整个仓库,但本快速入门和后续教程只需要其中的示例)
# Clone the repository to get the example code:
git clone -b v1.71.0 --depth 1 --shallow-submodules https://github.com/grpc/grpc
# Navigate to the "hello, world" Ruby example:
cd grpc/examples/ruby
运行 gRPC 应用
在 examples/ruby
目录下
运行服务器
ruby greeter_server.rb
在另一个终端中运行客户端
ruby greeter_client.rb
恭喜!您刚刚运行了一个使用 gRPC 的客户端-服务器应用。
更新 gRPC 服务
现在我们来看看如何通过在服务器上添加一个供客户端调用的额外方法来更新应用。我们的 gRPC 服务是使用协议缓冲区定义的;您可以在 基础教程中找到更多关于如何在 .proto
文件中定义服务的信息。现在您只需要知道,服务器和客户端“存根”都有一个 SayHello
RPC 方法,该方法接受来自客户端的 HelloRequest
参数并返回来自服务器的 HelloResponse
,并且此方法的定义如下
// 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;
}
记得保存文件!
生成 gRPC 代码
接下来我们需要更新应用使用的 gRPC 代码以使用新的服务定义。在 examples/ruby/
目录下
grpc_tools_ruby_protoc -I ../protos --ruby_out=lib --grpc_out=lib ../protos/helloworld.proto
这会重新生成 lib/helloworld_services_pb.rb
文件,其中包含我们生成的客户端和服务器类。
更新服务器
在同一目录下,打开 greeter_server.rb
。实现新方法如下
class GreeterServer < Helloworld::Greeter::Service
def say_hello(hello_req, _unused_call)
Helloworld::HelloReply.new(message: "Hello #{hello_req.name}")
end
def say_hello_again(hello_req, _unused_call)
Helloworld::HelloReply.new(message: "Hello again, #{hello_req.name}")
end
end
更新客户端
在同一目录下,打开 greeter_client.rb
。调用新方法如下
def main
stub = Helloworld::Greeter::Stub.new('localhost:50051', :this_channel_is_insecure)
user = ARGV.size > 0 ? ARGV[0] : 'world'
message = stub.say_hello(Helloworld::HelloRequest.new(name: user)).message
p "Greeting: #{message}"
message = stub.say_hello_again(Helloworld::HelloRequest.new(name: user)).message
p "Greeting: #{message}"
end
运行!
就像之前一样,在 examples/ruby
目录下
运行服务器
ruby greeter_server.rb
在另一个终端中运行客户端
ruby greeter_client.rb