中止 GRPC Ruby 客户端中的 GRPC 服务器流连接

Aborting a GRPC Server Stream Connection in GRPC Ruby Client

将 grpc 定义的服务视为:

rpc :StreamingEvents, StreamingEventRequest, stream(StreamingEventResponse)

并利用客户端连接到此服务,与此类似:

call = stub.streaming_events(StreamingEventRequest.new)

call.each do |response|
  pp response
end

如果我们要在单独的线程中生成调用,那么处理终止我们不再想再使用的永远运行的 grpc 连接的正确方法是什么?有没有连接或者流量控制的方法可以调用?

深入研究源代码,了解这一切的工作原理。如果你想用流控制做任何高级的事情,你必须传入 return_op 参数来接收一个操作符对象来控制流。这是一些示例代码:

传球方法:

op = stub.streaming_events(StreamingEventRequest.new, return_op: true) do |response|
  pp response
end

t = Thread.new do
  op.execute
rescue GRPC::Cancelled => e
  puts "this will terminate with an exception when we hit cancel - #{e}"
end

# controls for the operation
op.status
op.cancelled?
op.cancel # terminates connection and raises GRPC::Cancelled in the thread.

枚举器示例:

op = stub.streaming_events(StreamingEventRequest.new, return_op: true)

t = Thread.new do
  call = op.execute
  call.each do |response|
    pp response
  end
rescue GRPC::Cancelled => e
  puts "this will terminate with an exception when we hit cancel - #{e}"
end

# controls for the operation
op.status
op.cancelled?
op.cancel # terminates connection and raises GRPC::Cancelled in the thread.