我正在创建具有同步长寿命 GET 请求的 grpc python 客户端:
def main():
with grpc.insecure_channel(target='localhost:50051') as channel:
stub = hello_pb2_grpc.HelloStub(channel)
def signal_handler(signal, frame):
print("")
logging.warning("Interrupt signal. Exiting!")
channel.close()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
...
while True:
logging.info("Sending request for control")
try:
resp = stub.GetControl(hello_pb2.GetControlRequest(
node=node_id
))
print("Got response: {}".format(resp))
...
如果用户用Ctrl-C关闭python客户端并重新启动客户端,它将重新连接到不同端口的grpc服务器。
问题是:客户端应该如何通知grpc服务器它的退出,以便服务器应该“丢弃”之前的连接?
在几次客户端重新连接后,从服务器日志中我可以看到服务器尝试向不存在的对等方发送响应而没有任何错误:
INFO[0153] finished unary call with code OK grpc.code=OK grpc.method=GetControl grpc.service=world.World grpc.start_time="2021-02-19T12:41:17+01:00" grpc.time_ms=75479.79 peer.address="127.0.0.1:59976" span.kind=server system=grpc
INFO[0159] finished unary call with code OK grpc.code=OK grpc.method=GetControl grpc.service=world.World grpc.start_time="2021-02-19T12:41:05+01:00" grpc.time_ms=94089.74 peer.address="127.0.0.1:59862" span.kind=server system=grpc
注意:对等地址/端口不同。
使用客户端异步方法stub.GetControl会立即返回future
,可以随时取消future.cancel()
答案 0 :(得分:0)
cancel API 仅在 async 方法中可用。同步 API 旨在在返回之前完成所有工作,因此无法取消。顺便说一句,如果你想通知服务器,为什么不显式发送一个 RPC 呢?您使用的 GetControl
方法是一元调用,应该不会花很长时间完成。如果您希望在客户端/服务器之间进行更具交互性的通信,请尝试使用流式 RPC API。