zoukankan      html  css  js  c++  java
  • Tornado异步IO

    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的好机会……

  • 相关阅读:
    解密:腾讯如何打造一款实时对战手游
    哪是来的自尊心
    NODEJS 在Centos下面的自动启动
    nodejs的安装与配置
    基于Centos7+Nginx+Tomcat8的负载均衡服务器的搭建
    门店管理系统架构-(1)
    PHP 使用编码树,生成easyui中的tree样式
    Apache 打开网页的时候等待时间过长的解决方案
    Apache2.4开启GZIP功能
    Apache+Tomcat实现负载均衡
  • 原文地址:https://www.cnblogs.com/Finley/p/5510114.html
Copyright © 2011-2022 走看看