我一定做错了...我的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()
上阻塞了,但是我的问题是:我可以更改/优化Python客户端吗?这样它可以多次调用我的服务器,而无需等待第一个返回?
答案 0 :(得分:1)
您可以像这样在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()
proto
syntax = "proto3";
package asynch;
service DuckService {
rpc Quack (QuackRequest) returns (QuackResponse);
}
message QuackRequest {
int32 quackTimes = 1;
}
message QuackResponse {
string quackMsg = 1;
}