在python中从客户端关闭grpc服务器

时间:2019-12-10 07:15:21

标签: python grpc grpc-python


我有一个gRPC HelloWorld服务器正在运行,如官方入门指南(https://grpc.io/docs/quickstart/python/)中所示。 我现在想通过调用服务器方法从客户端关闭/终止服务器。
我知道可以做到这一点,因为我阅读了有关如何在c ++中执行此操作的文章。 How to shutdown gRPC server from Client (using RPC function)

对于客户端和服务器,我的编程语言都是python。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

就像在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()