如何在一个混合了 @gen.coroutine 和 async def 的 Tornado 应用中实现无缝调用?

解读

国内一线互联网公司在面试高并发方向时,常把“老代码里全是 @gen.coroutine,新业务想用 async def,如何不重构老代码又能让两者互调”作为分水岭问题。
它考察三点:

  1. 是否真正理解 Tornado 的“Future 统一协议”——无论哪种协程,最终都归结为 tornado.concurrent.Future;
  2. 是否知道 IOLoop 的 add_future/ensure_future 接口,以及 asyncio 的 run_in_executor、ensure_future 的对应关系;
  3. 能否给出可落地的灰度方案,而不是纸上谈兵。

答不到“Future 互转 + 事件循环融合”这一层,基本会被判定为“只写过 Demo”。

知识点

  1. Tornado 的 Future 与 asyncio.Future 在 5.0 之后已双向兼容,但 IOLoop 与 asyncio loop 仍可能不是同一个对象。
  2. @gen.coroutine 生成的是 generator,需要 gen.convert_yielded 把 yield 结构转成 Future;async def 生成的是 coroutine object,需要 asyncio.ensure_future 包一层。
  3. IOLoop.current().add_future 可以把任意 Future 丢到当前循环,保证不跨线程。
  4. 在 async def 里想调用 @gen.coroutine,用 tornado.platform.asyncio.to_asyncio_future 或手动 yield from gen.coroutine 函数;反过来在 @gen.coroutine 里想调 async def,用 IOLoop.current().run_in_executor 或 tornado.gen.Task+asyncio.ensure_future 包一下即可。
  5. 生产环境建议统一入口:启动阶段 tornado.platform.asyncio.AsyncIOMainLoop().install(),让 IOLoop 与 asyncio loop 合二为一,后续无需再转。

答案

  1. 启动时做一次性融合
import asyncio
from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().install()   # IOLoop 与 asyncio loop 同一对象
  1. 在 async def 中调用遗留 @gen.coroutine
from tornado import gen
class NewHandler(tornado.web.RequestHandler):
    async def get(self):
        # old_service 是 @gen.coroutine 装饰的函数
        ret = await gen.coroutine(old_service)()
        self.finish(ret)
  1. 在 @gen.coroutine 中调用新 async def
@gen.coroutine
def legacy_handler(self):
    # new_service 是 async def 函数
    ret = yield asyncio.ensure_future(new_service())
    return ret
  1. 若不想改老代码,可写通用桥接器
def any_to_future(co):
    if asyncio.iscoroutine(co):
        return asyncio.ensure_future(co)
    if gen.is_generator(co):
        return gen.convert_yielded(co)
    return co

调用端统一 await any_to_future(func()),实现零感知切换。

  1. 压测验证:wrk 长连接 10 k,QPS 无衰减,CPU 无额外开销,即视为无缝。

拓展思考

  1. 灰度迁移策略:
    先在新链路统一 async def,老链路保持 @gen.coroutine;通过 any_to_future 桥接,单周迭代即可上线;逐步把老链路单元测试改成 pytest-asyncio,覆盖率 90 % 后批量替换。
  2. 多核利用:
    融合后仍用 tornado.process.fork_processes,但子进程里不再调用 asyncio.set_event_loop,避免重复 install;配合 Gunicorn + uvloop 可再提 15 % 性能。
  3. 异常链保留:
    桥接时加 sys.exc_info() 透传,否则 Sentry 里会出现“coroutine was never awaited” 匿名异常,排查困难。
  4. 兼容 Python 3.12:
    3.12 移除 @asyncio.coroutine,Tornado 6.4 已标记 @gen.coroutine 为 deprecated,团队应制定 6 个月下线计划,防止未来版本崩溃。