Python gRPC 健康检查

Kri*_*har 8 grpc grpc-python

我正在尝试学习 gRPC 并实现与教程中相同的代码。想知道如何向其添加 gRPC 健康检查。

偶然发现了这一点,但对如何编写 gRPC 健康检查一无所知。

小智 6

经过几个小时的搜索我发现了这个。要检查 gRPC 服务器的运行状况,您必须将 healthCheckService 添加到现有服务器。因此现有的服务器上将运行多个服务。

这里解释了如何在同一服务器中添加多个服务的示例。

示例服务器:

# pip install grpcio-health-checking
from grpc_health.v1 import health
from grpc_health.v1 import health_pb2
from grpc_health.v1 import health_pb2_grpc

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  
# your normal service, that the server is supposed to run
helloworld_pb2.add_GreeterServicer_to_server(_GreeterServicer(), server)
  
# health check service - add this service to server
health_pb2_grpc.add_HealthServicer_to_server(
    health.HealthServicer(), server)

server.add_insecure_port('[::]:50051')
server.start()
Run Code Online (Sandbox Code Playgroud)


Ric*_*lle 4

随附的单元测试可以作为很好的参考。

        def start_server(self, non_blocking=False, thread_pool=None):
            self._thread_pool = thread_pool
            self._servicer = health.HealthServicer(
                experimental_non_blocking=non_blocking,
                experimental_thread_pool=thread_pool)
            self._servicer.set('', health_pb2.HealthCheckResponse.SERVING)
            self._servicer.set(_SERVING_SERVICE,
                               health_pb2.HealthCheckResponse.SERVING)
            self._servicer.set(_UNKNOWN_SERVICE,
                               health_pb2.HealthCheckResponse.UNKNOWN)
            self._servicer.set(_NOT_SERVING_SERVICE,
                               health_pb2.HealthCheckResponse.NOT_SERVING)
            self._server = test_common.test_server()
            port = self._server.add_insecure_port('[::]:0')
            health_pb2_grpc.add_HealthServicer_to_server(
                self._servicer, self._server)
            self._server.start()
Run Code Online (Sandbox Code Playgroud)

在应用程序服务器的主服务程序类中保留对运行状况服务程序的引用。然后,set()在适当的时间调用该方法,例如启动完成时或进入无法处理请求的状态时。但请注意,这使用了一些实验性功能,以确保附加的运行状况服务程序不会导致应用程序级请求匮乏。