【问题标题】:run tornado with aiomysql in multi-process mode在多进程模式下使用 aiomysql 运行 tornado
【发布时间】:2017-03-13 15:37:17
【问题描述】:

我一直在尝试使用以下代码在多进程模式下使用 aiomysql 运行 tornado

@asyncio.coroutine
def get_mysql_connection(loop):
    return (yield from aiomysql.create_pool(host=host,port=3306,user=user, password=pass, db=db, loop=loop))


if __name__ == "__main__":
    tornado.platform.asyncio.AsyncIOMainLoop().install()
    ioloop = asyncio.get_event_loop()
    mysql = ioloop.run_until_complete(get_mysql_connection(ioloop))
    options.parse_config_file("app.conf")
    app = make_app(mysql)
    print('listening on %s:%s...' %(options.host, options.port))
    server = tornado.httpserver.HTTPServer(app)
    server.listen(options.port)
    server.start(0) #this is my problem
    ioloop.run_forever()

但我不断收到以下错误

RuntimeError: Cannot run in multiple processes: IOLoop instance has already been initialized. You cannot call IOLoop.instance() before calling start_processes()

除了ioloop.start(0) 行之外,一切都运行良好,是否可以让aiomysqltornado 这两个库在多进程模式下正常工作?如果没有,我的其他选择是什么

Tornado 版本 4.4.2

python 版本 3.6.0

aiomysql 0.0.9版

【问题讨论】:

    标签: python-3.x tornado python-asyncio


    【解决方案1】:

    如消息所述,只有在 IOLoop 初始化之前 才能派生工作进程。这对 AsyncIOMainLoop 来说有点微妙,因为您想尽早安装它。解决方案是按以下顺序启动您的程序:

    tornado.options.parse_config_file(...)
    socks = tornado.netutil.bind_sockets(options.port, options.host)
    tornado.process.fork_processes(0)
    tornado.asyncio.AsyncIOMainLoop().install()
    # Initialize the rest of your app, create the HTTPServer, 
    # and instead of listen() or start(), do
    server.add_sockets(socks)
    

    我的其他选择是什么

    在我看来,最好使用像 supervisord 这样的外部进程管理器,而不是在您的应用程序中分叉多个进程。这避免了大多数这些初始化顺序陷阱。

    【讨论】:

    • 您的代码工作正常,但服务器立即退出,所以我不得不使用asyncio.get_event_loop().run_forever().start() 运行asyncio 事件循环
    • 是的,您仍然需要像往常一样启动事件循环。关于“instead of start()”的评论指的是HTTPServer.start(),而不是IOLoop.start()(或get_event_loop().run_forever()
    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 2023-04-08
    • 2016-06-20
    • 2018-10-30
    相关资源
    最近更新 更多