我有一个 gRPC HelloWorld 服务器运行,如官方入门指南( https://grpc.io/docs/quickstart/python/ )所示。
我现在想从客户端关闭/终止服务器,可能是通过调用服务器方法。
我知道这是可以做到的,因为我阅读了这篇关于如何在 C++ 中做到这一点的文章。 How to shutdown gRPC server from Client (using RPC function)
我的编程语言是客户端和服务器的python。任何帮助都感激不尽。
最佳答案
就像在 C++ 中一样,调用 Server.stop()
从处理程序将有问题。相反,您应该使用例如 threading.Event
在您的服务程序线程和处理程序线程之间进行协调。 .
在你的主线程中,做类似的事情
stop_event = threading.Event()
server = grpc.server(futures.ThreadPoolExecutor())
foo_pb2_grpc.add_FooServicer_to_server(Foo(stop_event), server)
server.add_insecure_port(...)
server.start()
stop_event.wait()
server.stop()
然后在您的服务程序中,在请求关闭时设置事件:
class Foo(foo_pb2_grpc.FooServicer):
def __init__(self, stop_event):
self._stop_event = stop_event
def Stop(self, request, context):
self._stop_event.set()
return foo_pb2.ShutdownResponse()
关于python - 如何从python中的gRPC客户端关闭gRPC服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59262044/