我一定是做错了什么……我的 gRPC 服务器是在 node.js 中实现的:
function handler(call, callback) {
console.log('Received request at ' + Date.now());
setTimeout(() => {
callback({ message: 'Done and done' });
}, 100);
}
Run Code Online (Sandbox Code Playgroud)
如果我在 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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
但是,使用service.future从 Python 调用服务器我可以看到服务器仅在前一个返回后接收请求:
for _ in range(1000):
message = Message(data=data)
resp = client.doit.future(message)
resp = resp.result()
resps.append(resp)
Run Code Online (Sandbox Code Playgroud)
我知道 Node 的 IO 范式是不同的(一切都是异步的;事件循环;等等),上面的 Python 示例阻止了out.result(),但我的问题是:我可以更改/优化 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()
Run Code Online (Sandbox Code Playgroud)
原型
syntax = "proto3";
package asynch;
service DuckService {
rpc Quack (QuackRequest) returns (QuackResponse);
}
message QuackRequest {
int32 quackTimes = 1;
}
message QuackResponse {
string quackMsg = 1;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4494 次 |
| 最近记录: |