gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:13 25 4
gpt4 key购买 nike

我一定是做错了什么……我的 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 调用服务器我可以看到服务器只在前一个请求返回后才收到请求:

for _ in range(1000):
message = Message(data=data)
resp = client.doit.future(message)
resp = resp.result()
resps.append(resp)

我知道 Node 的 IO 范式是不同的(一切都是异步的;事件循环;等等),上面的 Python 示例在 out.result() 上阻塞,但我的问题是:can 可以我更改/优化了 Python 客户端,以便它可以对我的服务器进行多次调用,而无需等待第一个调用返回?

最佳答案

您可以像这样在 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()

原型(prototype)

syntax = "proto3";

package asynch;

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

message QuackRequest {
int32 quackTimes = 1;
}

message QuackResponse {
string quackMsg = 1;
}

关于python - 如何在 Python 中进行异步 gRPC 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com