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

  • 相关阅读:
    设计模式之观察者模式
    设计模式之模板方法模式
    设计模式之代理模式(全面讲解)
    设计模式之工厂模式(包含三种模式)
    设计模式之单例模式(包含三种方式)
    opencv+vs2015 堆内存析构异常
    用python来压缩文件
    GPT安装ubuntu的问题
    Two Sum and add Two Numbers
    [LeetCode] Palindrome Partitioning II
  • 原文地址:https://www.cnblogs.com/Finley/p/5510114.html
Copyright © 2011-2022 走看看