异步链接的GRPC呼叫



是否有一种直接的方法来异步链中GRPC在Python中调用?

这感觉就像"应该"可行的东西,但我似乎找不到。

这是我认为我应该能够做的事情的大概:

class MyServer(my_grpc.MyServicer):
  def __init__(self, child_stub):
    self.child_stub_ = child_stub
  def MyMethod(self, request, context):
    child_result = self.child_stub_.ChildMethod.future(my_grpc.ChildMethodParams())
    child_result.add_done_callback(something_that_completes_MyMethod)
    return presumably_something

我在这里缺少什么吗?感觉这是一个常见的用例,但我似乎找不到文档中与之相关的任何内容。

编辑:我相信您正在尝试通过一个请求/响应设置向一个请求发送两个响应,我认为这是不可能的。相反,您应该执行一个单一的请求和流响应,这将允许许多响应。

客户端

import grpc
import test_pb2_grpc as pb_grpc
import test_pb2 as pb2
def test():
    channel = grpc.insecure_channel('localhost:50051')
    stub = pb_grpc.TestStub(channel=channel)
    for response in stub.Produce(pb2.Empty()):
        print(response.result)
if __name__ == '__main__':
    test()

服务器

import test_pb2_grpc as pb_grpc
import test_pb2 as pb2
import time
import grpc
from concurrent import futures

class test_servcie(pb_grpc.TestServicer):
    def Produce(self, request, context):
        my_method_results = [50, 200]
        for result in my_method_results:
            yield pb2.Resp(result=result)

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    pb_grpc.add_TestServicer_to_server(test_servcie(), server)
    server.add_insecure_port('[::]:50051')
    print("service started")
    server.start()
    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

原始

syntax = "proto3";
package api;

service Test {
    rpc Produce (Empty) returns (stream Resp);
}
message Empty {}

message Resp{
    int32 result = 1;
}

最新更新