基础教程
gRPC Ruby 基础教程简介。
基础教程
本教程为 Ruby 程序员提供了 gRPC 使用入门基础介绍。
通过阅读本示例,您将学习如何
- 在 .proto 文件中定义服务。
- 使用协议缓冲区编译器生成服务器和客户端代码。
- 使用 Ruby gRPC API 为您的服务编写一个简单的客户端和服务器。
本教程假设您已阅读 gRPC 简介 并熟悉 协议缓冲区。请注意,本教程中的示例使用 proto3 版本的协议缓冲区语言:您可以在 proto3 语言指南 中找到更多信息。
为什么使用 gRPC?
我们的示例是一个简单的路线地图应用程序,它允许客户端获取其路线上的特征信息,创建其路线摘要,并与服务器和其他客户端交换交通更新等路线信息。
使用 gRPC,我们可以在一个 .proto
文件中一次性定义服务,并以 gRPC 支持的任何语言生成客户端和服务器,这些客户端和服务器可以在从大型数据中心内部的服务器到您自己的平板电脑等各种环境中运行——不同语言和环境之间通信的所有复杂性都由 gRPC 为您处理。我们还可以获得使用协议缓冲区的全部优势,包括高效的序列化、简单的 IDL 和易于更新的接口。
示例代码和设置
本教程的示例代码位于 grpc/grpc/examples/ruby/route_guide 中。要下载示例,请运行以下命令克隆 grpc
仓库
git clone -b v1.71.0 --depth 1 --shallow-submodules https://github.com/grpc/grpc
cd grpc
然后将当前目录更改为 examples/ruby/route_guide
cd examples/ruby/route_guide
您还应该安装相关工具以生成服务器和客户端接口代码——如果您尚未安装,请按照 快速入门 中的设置说明进行操作。
定义服务
我们的第一步(正如您从 gRPC 简介 中了解到的)是使用 协议缓冲区 定义 gRPC 服务 以及方法的 请求 和 响应 类型。您可以在 examples/protos/route_guide.proto
中看到完整的 `.proto` 文件。
要定义服务,请在您的 .proto 文件中指定一个名为 service
的定义
service RouteGuide {
...
}
然后您在服务定义内部定义 rpc
方法,指定其请求和响应类型。gRPC 允许您定义四种服务方法,所有这些方法都在 RouteGuide
服务中使用
一种 简单的 RPC,客户端使用存根向服务器发送请求并等待响应返回,就像普通函数调用一样。
// Obtains the feature at a given position. rpc GetFeature(Point) returns (Feature) {}
一种 服务器端流式 RPC,客户端向服务器发送请求并获得一个流,用于读取一系列消息。客户端从返回的流中读取直到没有更多消息。正如您在示例中看到的那样,通过在 响应 类型之前放置
stream
关键字来指定服务器端流式方法。// Obtains the Features available within the given Rectangle. Results are // streamed rather than returned at once (e.g. in a response message with a // repeated field), as the rectangle may cover a large area and contain a // huge number of features. rpc ListFeatures(Rectangle) returns (stream Feature) {}
一种 客户端流式 RPC,客户端写入一系列消息并将其发送到服务器,同样使用提供的流。客户端完成写入消息后,会等待服务器读取所有消息并返回其响应。通过在 请求 类型之前放置
stream
关键字来指定客户端流式方法。// Accepts a stream of Points on a route being traversed, returning a // RouteSummary when traversal is completed. rpc RecordRoute(stream Point) returns (RouteSummary) {}
一种 双向流式 RPC,双方都使用读写流发送一系列消息。两个流独立运行,因此客户端和服务器可以按任何顺序读写:例如,服务器可以等待接收所有客户端消息后再写入其响应,或者它可以交替读取消息然后写入消息,或采用其他一些读写组合。每个流中消息的顺序会保留。通过在请求和响应之前都放置
stream
关键字来指定这种类型的方法。// Accepts a stream of RouteNotes sent while a route is being traversed, // while receiving other RouteNotes (e.g. from other users). rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
我们的 .proto
文件还包含服务方法中使用的所有请求和响应类型的协议缓冲区消息类型定义——例如,这是 Point
消息类型
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
生成客户端和服务器代码
接下来,我们需要从我们的 .proto 服务定义中生成 gRPC 客户端和服务器接口。我们使用协议缓冲区编译器 protoc
和一个特殊的 gRPC Ruby 插件来完成此操作。
如果您想自己运行,请确保已安装 gRPC 和 protoc。
完成后,可以使用以下命令生成 ruby 代码。
grpc_tools_ruby_protoc -I ../../protos --ruby_out=../lib --grpc_out=../lib ../../protos/route_guide.proto
运行此命令会在 lib
目录中重新生成以下文件
lib/route_guide.pb
定义了一个模块Examples::RouteGuide
- 这包含所有用于填充、序列化和检索我们的请求和响应消息类型的协议缓冲区代码
lib/route_guide_services.pb
,使用存根和服务类扩展了Examples::RouteGuide
- 一个
Service
类,用作定义 RouteGuide 服务实现的基类 - 一个
Stub
类,可用于访问远程 RouteGuide 实例
- 一个
创建服务器
首先,我们来看看如何创建一个 RouteGuide
服务器。如果您只对创建 gRPC 客户端感兴趣,可以跳过本节,直接前往 创建客户端 (尽管您可能仍然觉得它很有趣!)。
让我们的 RouteGuide
服务正常工作有两个部分
- 实现从服务定义生成的服务接口:执行服务的实际“工作”。
- 运行一个 gRPC 服务器以监听来自客户端的请求并返回服务响应。
您可以在 examples/ruby/route_guide/route_guide_server.rb 中找到我们的示例 RouteGuide
服务器。让我们仔细看看它是如何工作的。
实现 RouteGuide
如您所见,我们的服务器有一个 ServerImpl
类,它扩展了生成的 RouteGuide::Service
# ServerImpl provides an implementation of the RouteGuide service.
class ServerImpl < RouteGuide::Service
ServerImpl
实现了我们所有的服务方法。让我们先看看最简单的类型 GetFeature
,它只是从客户端获取一个 Point
,并在 Feature
中返回数据库中相应的特征信息。
def get_feature(point, _call)
name = @feature_db[{
'longitude' => point.longitude,
'latitude' => point.latitude }] || ''
Feature.new(location: point, name: name)
end
该方法被传递一个用于 RPC 的 _call,客户端的 Point
协议缓冲区请求,并返回一个 Feature
协议缓冲区。在该方法中,我们使用适当的信息创建 Feature
,然后将其 return
返回。
现在让我们看一个更复杂一些的——流式 RPC。ListFeatures
是一个服务器端流式 RPC,所以我们需要向客户端发送多个 Feature
。
# in ServerImpl
def list_features(rectangle, _call)
RectangleEnum.new(@feature_db, rectangle).each
end
如您所见,这里的请求对象是一个 Rectangle
,客户端希望在此区域内查找 Feature
,但我们不是返回一个简单的响应,而是需要返回一个产生响应的 Enumerator。在该方法中,我们使用一个辅助类 RectangleEnum
,作为 Enumerator
的实现。
类似地,客户端流式方法 record_route
使用一个 Enumerable,但在这里它是从 `call` 对象中获取的,我们在前面的示例中忽略了它。call.each_remote_read
依次产生客户端发送的每条消息。
call.each_remote_read do |point|
...
end
最后,让我们看看我们的双向流式 RPC route_chat
。
def route_chat(notes)
RouteChatEnumerator.new(notes, @received_notes).each_item
end
在这里,方法接收一个 Enumerable,但也返回一个产生响应的 Enumerator。虽然每一方总是会按照消息写入的顺序接收到对方的消息,但客户端和服务器都可以按任何顺序读写——流完全独立运行。
启动服务器
实现所有方法后,我们还需要启动一个 gRPC 服务器,以便客户端能够实际使用我们的服务。以下代码片段展示了如何为 RouteGuide
服务执行此操作
port = '0.0.0.0:50051'
s = GRPC::RpcServer.new
s.add_http2_port(port, :this_port_is_insecure)
GRPC.logger.info("... running insecurely on #{port}")
s.handle(ServerImpl.new(feature_db))
# Runs the server with SIGHUP, SIGINT and SIGQUIT signal handlers to
# gracefully shutdown.
# User could also choose to run server via call to run_till_terminated
s.run_till_terminated_or_interrupted([1, 'int', 'SIGQUIT'])
如您所见,我们使用 GRPC::RpcServer
构建并启动服务器。为此,我们
- 创建服务实现类
ServerImpl
的实例。 - 使用构建器的
add_http2_port
方法指定我们想要用于监听客户端请求的地址和端口。 - 在
GRPC::RpcServer
中注册我们的服务实现。 - 调用
GRPC::RpcServer
上的run
方法为我们的服务创建并启动一个 RPC 服务器。
创建客户端
在本节中,我们将介绍如何为 RouteGuide
服务创建一个 Ruby 客户端。您可以在 examples/ruby/route_guide/route_guide_client.rb 中看到完整的示例客户端代码。
创建存根
要调用服务方法,我们首先需要创建一个 存根(stub)。
我们使用从 `.proto` 生成的 RouteGuide
模块的 Stub
类。
stub = RouteGuide::Stub.new('localhost:50051')
调用服务方法
现在让我们看看如何调用服务方法。请注意,gRPC Ruby 只提供了每个方法的 阻塞/同步 版本:这意味着 RPC 调用会等待服务器响应,并且要么返回响应,要么引发异常。
简单的 RPC
调用简单的 RPC GetFeature
几乎就像调用本地方法一样直接。
GET_FEATURE_POINTS = [
Point.new(latitude: 409_146_138, longitude: -746_188_906),
Point.new(latitude: 0, longitude: 0)
]
..
GET_FEATURE_POINTS.each do |pt|
resp = stub.get_feature(pt)
...
p "- found '#{resp.name}' at #{pt.inspect}"
end
如您所见,我们创建并填充一个请求协议缓冲区对象(在本例中为 Point
),并创建一个响应协议缓冲区对象供服务器填充。最后,我们在存根上调用该方法,将上下文、请求和响应传递给它。如果方法返回 OK
,则我们可以从响应对象中读取服务器的响应信息。
流式 RPC
现在让我们看看流式方法。如果您已经阅读过 创建服务器,其中一些内容可能看起来很熟悉——流式 RPC 在两端以类似的方式实现。这里是我们调用服务器端流式方法 list_features
的地方,它返回一个 Feature
的 Enumerable
。
resps = stub.list_features(LIST_FEATURES_RECT)
resps.each do |r|
p "- found '#{r.name}' at #{r.location.inspect}"
end
使用多个线程和 return_op: true
标志可以实现 RPC 流的非阻塞使用。当传递 return_op: true
标志时,RPC 的执行会延迟并返回一个 Operation
对象。然后可以在另一个线程中通过调用操作的 execute
函数来执行 RPC。主线程可以利用上下文方法和获取器(如 status
、cancelled?
和 cancel
)来管理 RPC。这对于会长时间阻塞主线程的持久或长时间运行的 RPC 会话非常有用。
op = stub.list_features(LIST_FEATURES_RECT, return_op: true)
Thread.new do
resps = op.execute
resps.each do |r|
p "- found '#{r.name}' at #{r.location.inspect}"
end
rescue GRPC::Cancelled => e
p "operation cancel called - #{e}"
end
# controls for the operation
op.status
op.cancelled?
op.cancel # attempts to cancel the RPC with a GRPC::Cancelled status; there's a fundamental race condition where cancelling the RPC can race against RPC termination for a different reason - invoking `cancel` doesn't necessarily guarantee a `Cancelled` status
客户端流式方法 record_route
与此类似,只是在那里我们向服务器传递一个 Enumerable
。
...
reqs = RandomRoute.new(features, points_on_route)
resp = stub.record_route(reqs.each)
...
最后,让我们看看我们的双向流式 RPC route_chat
。在这种情况下,我们将 Enumerable
传递给方法,并返回一个 Enumerable
。
sleeping_enumerator = SleepingEnumerator.new(ROUTE_CHAT_NOTES, 1)
stub.route_chat(sleeping_enumerator.each_item) { |r| p "received #{r.inspect}" }
虽然这个例子没有很好地展示出来,但每个 enumerable 都是独立的——客户端和服务器都可以按任何顺序读写——流完全独立运行。
试一试!
从示例目录工作
cd examples/ruby
构建客户端和服务器
gem install bundler && bundle install
运行服务器
bundle exec route_guide/route_guide_server.rb ../python/route_guide/route_guide_db.json
注意
route_guide_db.json
文件实际上是语言无关的,它恰好位于 python
文件夹中。从另一个终端运行客户端
bundle exec route_guide/route_guide_client.rb ../python/route_guide/route_guide_db.json