您的位置:首页 > 其它

Tornado异步IO

2016-05-19 20:52 302 查看
Tornado提供了强大的异步IO机制,提高了服务器的响应能力.

@tornado.web.asynchronous

tornado默认在处理函数返回时关闭链接,
@tornado.web.asynchronous
修饰器使得连接保持开启, 即修饰器将RequestHandler 的 _auto_finish 属性置为 false.

需要调用RequestHandler.finish()方法关闭连接。

class IndexHandler(tornado.web.RequestHandler):

def on_finish():
self.finish()

@tornado.web.asynchronous
def get(self):
self.write('Async Hello')
self.finish()

@tornado.gen.engine

Tornado 通过 @asynchronous decorator 来实现异步请求,但使用的时候必须将 RequestHandler 和 callback 分离开,tornado.gen 模块可以帮助我们在一个函数里完成这两个工作。

@tornado.gen使用python的generator来实现异步。

该修饰器必须包含在
@asynchronous
修饰器内层。

class GenAsyncHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
http_client = AsyncHTTPClient()
response = yield gen.Task(http_client.fetch, "http://example.com")
do_something_with_response(response)
self.render("template.html")

tornado.gen.Task(func, *args, **kwargs)


Task的构造器接受一个异步调用func(如http_client.fetch), 并把args和kwargs传给func.

在异步调用返回(发送消息)后yield Task对象,在异步调用返回结果赋给response,从下一行继续执行(和原生的Python协程相同).

注意Task的func必须是异步调用,否则仍会造成阻塞。

tornado自带的各种AsyncClient经常用于此种情形下。

@tornado.gen.coroutine

在tornado3发布之后,强化了coroutine的概念,在异步编程中,gen.coroutine替代了原来的gen.engine,两者的使用是基本一致的。

从调用者角度说,
@gen.coroutine
类似于
@return_future
@gen.engine
.

ioloop

Tornado依赖ioloop实现了非阻塞式(同步多路IO复用)的请求响应,ioloop采用epoll或者select实现。

理解非阻塞和异步io的好机会……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: