python grpc server获取status,Python gRPC服务器未启动

本文探讨了使用Python和gRPC创建健康检查服务时遇到的问题,即GRPC服务器无法启动,尽管代码看起来正常。可能的原因是服务器实例在函数结束时被垃圾回收。解决办法涉及确保服务器在生命周期中持续运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I've create a gRPC server using proto3 and python to do basic health checking on a long running daemon. When I start my application though, it doesn't actually start the gRPC server. I was wondering if anyone could help identify why it doesn't start and serve the gRPC API

Proto Definition: health.proto

syntax = "proto3";

option java_multiple_files = true;

option java_package = "com.redacted.example.worker";

option java_outer_classname = "ExampleWorker";

option objc_class_prefix = "DSW";

package exampleworker;

service Worker {

rpc Health (Ping) returns (Pong) {}

}

// The request message containing PONG

message Ping {

string message = 1;

}

// The response message containing PONG

message Pong {

string message = 1;

}

Then I generated the python code using:

python -m grpc_tools.protoc -I=../protos --python_out=. --grpc_python_out=. ../protos/health.proto

This generated the health_pb2.py and health_pb2_grpc.py files. I next created a server file:

u"""Health server is used to create a new health monitoring GRPC server."""

from concurrent import futures

import logging

import grpc

import health_pb2

import health_pb2_grpc

# grpc related variables

grpc_host = u'[::]'

grpc_port = u'50001'

grpc_address = u'{host}:{port}'.format(host=grpc_host, port=grpc_port)

# logging related variables

logger = logging.getLogger(__name__)

logger.setLevel(logging.INFO)

class WorkerServicer(health_pb2_grpc.WorkerServicer):

u"""Provides methods that implement functionality of health server."""

def Health(self, request, context):

u"""Return PONG to say the Worker is alive."""

return health_pb2.Pong(message='PONG')

def serve_health_api():

u"""Create and start the GRPC server."""

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

health_pb2_grpc.add_WorkerServicer_to_server(WorkerServicer(), server)

logging.info(u'adding port {grpc_address}'.format(

grpc_address=grpc_address))

server.add_insecure_port(grpc_address)

server.start()

Then in my main run.py file:

#!mac/bin/python

"""Run is the local (non-wsgi) entrypoint to the flask application."""

from subscriber.worker import Worker

from redis import StrictRedis

from examplegrpc.health_server import serve_health_api

import logging

redis_host = 'localhost'

redis_port = 6379

redis_db = 0

redis_chan = 'deployment'

if __name__ == "__main__":

FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'

logging.basicConfig(format=FORMAT)

logger = logging.getLogger(__name__)

logger.setLevel(logging.INFO)

logger.debug('Creating redis client')

client = StrictRedis(host=redis_host, port=redis_port, db=redis_db)

w = Worker(client, [redis_chan])

try:

logger.info('Starting Health gRPC API...')

serve_health_api()

logger.info('Starting worker...')

w.run()

except KeyboardInterrupt:

logger.info('Exiting...')

The w.run() starts correctly to execute work off of a redis channel, but the gRPC server does not start as trying to access it with

channel = grpc.insecure_channel('localhost:{port}'.format(port=grpc_port))

stub = WorkerStub(channel)

ping = examplegrpc.health_pb2.Ping(message='PING')

health = stub.Health(ping)

starts

_Rendezvous: <_rendezvous of rpc that terminated with connect failed>

解决方案

It looks to me like what's happening is that your server is only assigned to a local field in your serve_health_api function, so when that function returns (immediately after having started the server) the server is garbage-collected and shut down.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值