import sys import os import grpc import logging import signal from concurrent import futures from loguru import logger # 因为在终端上运行会找不到根目录所以需要指明项目根目录 BASE_PATH = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, BASE_PATH) from user_srv.proto import user_pb2, user_pb2_grpc from user_srv.handler.user import UserService # 处理中断函数 def on_exit(signal, frame): logger.info("grpc server exit") # 服务注销逻辑....... sys.exit(0) def serve(): logger.add("logs/user_srv_{time}.log") # 多线程启动 server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) # 注册服务 user_pb2_grpc.add_UserServicer_to_server(UserService(), server) # 端口 server.add_insecure_port("[::]:50051") # 监听退出信号 """ windows下支持的信号是有限的: SIGINT ctrl+C终端 SIGTERM kill发出的软件终止 """ signal.signal(signal.SIGINT, on_exit) signal.signal(signal.SIGTERM, on_exit) logger.info(f"启动服务:http://127.0.0.1:50051") server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()