【python3】tornado高性能编程

  • 使用多进程充分利用cpu
  • 使用异步编程 asyncio
python 复制代码
import asyncio
import time
from abc import ABC
from concurrent.futures import ProcessPoolExecutor
from tornado import web, ioloop, gen


async def async_task(name):
    print(f"start: {name}")
    st = int(time.time())
    time.sleep(3)  # 模拟同步等待 
    await asyncio.sleep(3)  # 模拟异步等待
    result = f"task: {name}, start: {st}, end: {int(time.time())}"
    return result


def run_async_task(name):
    return asyncio.run(async_task(name))


class MainHandler(web.RequestHandler, ABC):
    executor = ProcessPoolExecutor()  # 进程池

    @gen.coroutine
    def get(self):
        task_name = self.get_argument("task", "task-1")
        result = yield self.executor.submit(run_async_task, task_name)
        self.write(result)


def make_app():
    return web.Application([
        (r"/", MainHandler),
    ])


if __name__ == '__main__':
    app = make_app()
    app.listen(8888)
    print("http://localhost:8888/?task=task-X")
    ioloop.IOLoop.current().start()
相关推荐
圆内~搁浅1 小时前
langchain本地知识库问答机器人集成本地知识库
数据库·langchain·机器人
早起的年轻人2 小时前
Docket Desktop 安装redis 并设置密码
数据库·redis·缓存
xlxxy_2 小时前
ABAP数据库表的增改查
开发语言·前端·数据库·sql·oracle·excel
清水加冰2 小时前
【MySQL】索引
数据库·mysql
qw9492 小时前
Redis(高阶篇)03章——缓存双写一致性之更新策略探讨
数据库·redis·缓存
IT猿手3 小时前
2025最新智能优化算法:鲸鱼迁徙算法(Whale Migration Algorithm,WMA)求解23个经典函数测试集,MATLAB
android·数据库·人工智能·算法·机器学习·matlab·无人机
m0_748234083 小时前
SQL Server 导入Excel数据
数据库
Ciderw4 小时前
MySQL日志undo log、redo log和binlog详解
数据库·c++·redis·后端·mysql·面试·golang
CT随4 小时前
Redis 存在线程安全问题吗?为什么?
数据库·redis·安全