快速入门

本指南通过一个简单的示例,帮助您开始在 Ruby 中使用 gRPC。

快速入门

本指南通过一个简单的示例,帮助您开始在 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.74.0 --depth 1 --shallow-submodules https://github.com/grpc/grpc
# Navigate to the "hello, world" Ruby example:
cd grpc/examples/ruby

运行 gRPC 应用程序

examples/ruby 目录下

  1. 运行服务器

    ruby greeter_server.rb
    
  2. 在另一个终端中,运行客户端

    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 目录下

  1. 运行服务器

    ruby greeter_server.rb
    
  2. 在另一个终端中,运行客户端

    ruby greeter_client.rb
    

接下来