2012-03-24 43 views
0

我刚想到龙卷风和事件驱动编程的非阻塞基础设施。其实我正在写一个简单的Web应用程序,它正在访问外部Web服务的HTTP-API。我明白为什么我应该调用这个API非阻塞。但是如果我只进行第一次非阻塞呼叫,那么是否存在任何缺点,以便IOLoop可以进一步循环?Tornado Blocking Code

例如:

@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() 

@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() 

回答

1

如果使用阻塞内龙卷风代码,相同的龙卷风过程不能过程中的任何其他请求,而任何阻塞代码正在等待。您的应用程序不会支持多个并发用户,即使阻止呼叫只需要100毫秒,仍然会是一个巨大的性能杀手。

如果写这个方式耗尽了你(这是对我来说),你可以使用龙卷风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")