【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 小时前
MES 系统 设备保养管理模块详细设计方案
运维·数据库
晚风_END3 小时前
Linux|操作系统|zfs文件系统的使用详解
linux·运维·服务器·数据库·postgresql·性能优化·宽度优先
晚风_END9 小时前
Linux|操作系统|最新版openzfs编译记录
linux·运维·服务器·数据库·spring·中间件·个人开发
dLYG DUMS9 小时前
DBeaver连接本地MySQL、创建数据库表的基础操作
数据库·mysql
苍煜10 小时前
MySQL分库分表和ES到底怎么选?
数据库·mysql·elasticsearch
茉莉玫瑰花茶10 小时前
Qt 信号与槽 [ 1 ]
开发语言·数据库·qt
czlczl2002092510 小时前
松散索引扫描/跳跃索引扫描
数据库·mysql·性能优化
星马梦缘12 小时前
数据库作战记录 实验7、8
数据库·sql·oracle
安逸sgr13 小时前
Hermes Agent + Obsidian 打造第二大脑(六):分层记忆系统的设计逻辑——L0/L1/L2/L3 四层记忆详解
数据库·agent·知识库·hermes·hermesagent
苍煜13 小时前
一篇讲懂分库分表:概念、spirngboot实战
数据库·oracle