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

标签 python grpc grpc-python

我有一个 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/

相关文章:

python - 如何从 Python 中的列表列表中删除所有无元素

go - Monorepo : How to consume a package from another project?

python - grpc-Python max_workers 限制同时进程数

python - 如何使用函数在python中导入变量?

python - 如何使用 cx_Oracle 在 Python 中返回 SQLPLUS 变量

javascript - 如何使用 beautifulsoup 从 js 和 Reactjs 获取数据?

python - grpc 字段 Message.Field .PeopleRequest.ages 的线路类型非法 : 2 (0 expected))

go - 将日志记录中心添加到 grpc

python-multithreading - gRPC + Thread 本地问题

c++ - GRPC CreateChannel() 错误无法获取默认 pem 根证书