Tornado 将阻塞任务用异步Handler委派给工作线程池

两个用 tornado.concurrent.run_on_executor 来实现把Handler 接到的任务分派到后台运行的例子

Tornado 将阻塞任务用异步Handler委派给工作线程池

MySQL:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import time

import tornado
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor   # `pip install futures` for python2

from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado import gen

MAX_WORKERS = 4


class Handler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)

    @run_on_executor
    def background_task(self, i):
        """ This will be executed in `executor` pool. """
        time.sleep(10)
        return i

    @gen.coroutine
    def get(self, idx):
        """ Request that asynchronously calls background task. """
        res = yield self.background_task(idx)
        self.write(res)


HTTPServer(Application([("/(\d+)", Handler)],debug=True)).listen(8888)

IOLoop.instance().start()

第二个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import datetime
import time

from tornado.ioloop import IOLoop
import tornado.web
from tornado import concurrent

executor = concurrent.futures.ThreadPoolExecutor(8)


class Handler(tornado.web.RequestHandler):

    def get(self):
        def task(arg):
            for i in range(10):
                time.sleep(1)
                print(arg, i)

        executor.submit(task, datetime.datetime.now())
        self.write('request accepted')


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


if __name__ == "__main__":
    app = make_app()
    app.listen(8000, '0.0.0.0')
    IOLoop.current().start()

本文网址: https://pylist.com/topic/167.html 转摘请注明来源

Suggested Topics

服务器推送技术 Tornado comet

long poll的原理是,客户端与服务器将建立一条长连接,也就是说,客户端会发出一个请求,而服务器,将阻塞请求,直到有数据需要传递,才会返回。 ...

在128M的VPS上配置mysql+Tornado+Nginx笔记

最近 123systems http://goo.gl/2Q0X2 又推出一年$10的便宜 VPS,128M内存,可以用来学习。在这样的vps 上放一个博客或做反向代理绰绰有余,买下后尝试配一个mysql+Tornado+Nginx 环境。...

Leave a Comment