문제

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. I understand why I should call this API non-blocking. But are there any disadvantages if I do just the first call non-blocking, so that the IOLoop can loop further?

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.

If writing this way is exhausting for you (it is for me), you can use tornado's gen module:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top