简体   繁体   English

龙卷风阻止代码

[英]Tornado Blocking Code

I just thought about the non-blocking infrastructure of tornado and event-driven programming. 我只是想到了龙卷风和事件驱动编程的非阻塞基础结构。 Actually I'm writing a simple webapp which is accessing a HTTP-API of an external webservice. 实际上,我正在写一个简单的Web应用程序,它正在访问外部Web服务的HTTP-API。 I understand why I should call this API non-blocking. 我了解为什么我应该将此API称为非阻塞。 But are there any disadvantages if I do just the first call non-blocking, so that the IOLoop can loop further? 但是,如果仅执行第一个调用非阻塞操作,则IOLoop可以进一步循环,是否有任何缺点?

For Example: 例如:

@tornado.web.asynchronous
def get(self):
    nonblocking_call1(self._callback)

def _callback(self, response):
    self.write(str(response))
    self.write(str(blocking_call2()))
    self.write(str(blocking_call3()))
    self.finish()

vs.

@tornado.web.asynchronous
def get(self):
    nonblocking_call1(self._nonblocking_callback1)

def _callback1(self, response):
    self.write(str(response))
    nonblocking_call2(self._nonblocking_callback2)

def _callback2(self, response):
    self.write(str(response))
    nonblocking_call3(self._nonblocking_callback3)

def _callback3(self, response):
    self.write(str(response))
    self.finish()

If you use blocking code inside tornado, the same tornado process can not process any other requests while any blocking code is waiting. 如果在龙卷风内部使用阻止代码,则在等待任何阻止代码的情况下,同一龙卷风进程无法处理任何其他请求。 Your app will not support more than one simultaneous user, and even if the blocking call only takes something like 100ms, it will still be a HUGE performance killer. 您的应用程序将不支持多个用户同时使用,即使阻塞调用仅花费100毫秒左右的时间,它仍将是巨大的性能杀手。

If writing this way is exhausting for you (it is for me), you can use tornado's gen module: 如果写这种方法对您来说很累(对我来说),则可以使用龙卷风的gen模块:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM