如何在 Python 中进行异步 gRPC 调用?

How to make async gRPC calls in Python?

我一定是做错了什么...我的 gRPC 服务器是在 node.js:

中实现的
function handler(call, callback) {
   console.log('Received request at ' + Date.now());
   setTimeout(() => {
      callback({ message: 'Done and done' });
   }, 100);
}

如果我在 Node 中调用它 1,000,我会在大约 100 毫秒内收到 1,000 个响应:

const resps = [];
for (let i = 0; i < 1000; i += 1) {
    client.doit({ data }, (err, resp) => {
      resps.push(resp);
      if (resps.length === 1000) {
        onDone();
      }
    });
}

但是,使用 service.future 从 Python 调用服务器我可以看到服务器仅在前一个请求 returned:

之后才收到请求
for _ in range(1000):
    message = Message(data=data)
    resp = client.doit.future(message)
    resp = resp.result()
    resps.append(resp)

我知道 Node 的 IO 范例是不同的(一切都是异步的;事件循环;等等),上面的 Python 示例在 out.result() 上阻塞,但我的问题是:我可以吗change/optimize Python 客户端,这样它就可以对我的服务器进行多次调用,而无需等待第一个 return?

您可以在 python 中进行异步一元调用,如下所示:

class RpcHandler:
    def rpc_async_req(self, stub):
        def process_response(future):
            duck.quack(future.result().quackMsg)

        duck = Duck()
        call_future = stub.Quack.future(pb2.QuackRequest(quackTimes=5)) #non-blocking call
        call_future.add_done_callback(process_response) #non-blocking call
        print('sent request, we could do other stuff or wait, lets wait this time. . .')
        time.sleep(12) #the main thread would drop out here with no results if I don't sleep
        print('exiting')

class Duck:
    def quack(self, msg):
        print(msg)


def main():
    channel = grpc.insecure_channel('localhost:12345')
    stub = pb2_grpc.DuckServiceStub(channel)
    rpc_handler = RpcHandler()
    rpc_handler.rpc_async_req(stub=stub)

if __name__ == '__main__':
    main()

原型

syntax = "proto3";

package asynch;

service DuckService {
    rpc Quack (QuackRequest) returns (QuackResponse);
}

message QuackRequest {
    int32 quackTimes = 1;
}

message QuackResponse {
    string quackMsg = 1;
}