aiohttp+uvloop+gunicorn

aiohttp+uvloop

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import asyncio
import uvloop
from aiohttp import web
from utils.logger_helper import LogFactory

logger = LogFactory.get_logger()

def main():
logger.info("Server Starting at {0};{1}".format(cfg.host, cfg.port))
app = web.Application()
setup_routes(app)
app.on_shutdown.append(shutdown)
web.run_app(app, host=cfg.host, port=cfg.port)

if __name__ == "__main__":
# 使用 uvloop 替换掉 asyncio 默认的事件循环
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

# 启动 Server
try:
main()
except Exception as e:
logger.error(e)

aiohttp+uvloop+gunicorn

main.py

1
2
3
4
5
6
7
# For Gunicorn
async def web_app():
logger.info("Server Starting at {0};{1}".format(cfg.host, cfg.port))
app = web.Application()
setup_routes(app)
app.on_shutdown.append(shutdown)
return app

gunicorn ... --worker-class aiohttp.worker.GunicornUVLoopWebWorker

在启动gunicorn的时候, 指定uvloop的worker-class即可

How to use uvloop in an asyncio application

1
2
3
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

How to use uvloop with Tornado

1
2
3
4
5
6
7
from tornado.platform.asyncio import AsyncIOMainLoop
import asyncio
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
AsyncIOMainLoop().install()
asyncio.get_event_loop().run_forever()

参考文档: