如何从python中的gRPC客户端关闭gRPC服务器?

Har*_*kar 3 python grpc grpc-python


我有一个 gRPC HelloWorld 服务器运行,如官方入门指南(https://grpc.io/docs/quickstart/python/)中所示。我现在想从客户端关闭/终止服务器,可能是通过调用服务器方法。
我知道这是可以做到的,因为我阅读了这篇关于如何在 C++ 中做到这一点的文章。如何从客户端关闭 gRPC 服务器(使用 RPC 功能)

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

Ric*_*lle 6

就像在 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()
Run Code Online (Sandbox Code Playgroud)

然后在您的服务程序中,在请求关闭时设置事件:

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()
Run Code Online (Sandbox Code Playgroud)