如果Grpc服务器与带踏板的烧瓶应用程序一起运行,则立即退出。

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (26)

我试图在单个应用程序和容器中运行FlaskRESTAPI和GRPCAPI,由于某种原因,GRPC服务器在启动后立即关闭。

So I have a simple Flask app that is serving few REST endpoints. It has two blueprints and bootstraps with pretty standard entrypoint:

#!/usr/bin/env python
from app import bootstrap

app_name = os.environ.get(C.KEYS.APP_NAME_KEY)
conf_data = bootstrap.get_conf_data(app_name)
flask_app = bootstrap.get_app(app_name, conf_data)
bootstrap.register_blueprints(flask_app)

if __name__ == '__main__':
    flask_app.run()

我已经创建了一个单独的模块,它实现了一个简单的GRPC接口,我希望在同一个应用程序和容器中的不同端口上同时运行这两个模块。默认的grpc服务器实现使用futures.ThreadPoolExecutor and is nonblocking, so I assume it should be able to run in the background of Flask app execution. gRPC server bootstrap looks like this:

import grpc
from concurrent import futures

from svc.auth_grpc import auth_pb2, auth_pb2_grpc


def start_server():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=1),
                         maximum_concurrent_rpcs=1)
    auth_pb2_grpc.add_AuthServiceServicer_to_server(AuthServiceServicer(),
                                                    server)
    server.add_insecure_port(f'0.0.0.0:9091')
    server.start()

And since my goal is to make gRPC and Flask coexist - I'm adding gRPC bootstrap to the application entrypoint like this:

if __name__ == '__main__':
    start_server()
    flask_app.run()

I expect that gRPC will start a thread and live in background indefinitely, while Flask will execute standard blocking werkzeug bootstrap and will live in foreground. All of this happens at the start, however the next second after Flask start the gRPC queue CompletionQueue receives a SHUTDOWN event and server quits.

I don't know why this event happens and what triggers it, and I cannot dig deeper into the CompletionQueue because it's Cython implementation underneath.

Separately gRPC server and Flask app run correctly with all the rest of code unchanged.

How do I make these two event loops coexist?

提问于
用户回答回答于

好吧,在函数完成server后,变量将被垃圾收集start_server。这就是gRPC服务器似乎立即关闭的原因。要解决此问题,可以使用全局变量来存储服务器对象。

此外,如果您认为此API设计不理想,请随时在GitHub repo https://github.com/grpc/grpc上提交问题。

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励