tornado接口阻塞导致主线程阻塞

tornado推荐是多进程+协程的方式运行,ioloop.current().start(),单个接口阻塞,会导致整个服务阻塞,所以一般接口逻辑中要使用非阻塞的方法。

比如time.sleep(5)应该更换为yield gen.sleep(5),这样就可以将资源让给其他接口处理,该接口仍然会阻塞,等同于time.sleep(5)

 

tornado接口阻塞导致主线程阻塞,将启动进程设为与cpu核数相同,将调用方法改为异步,改为异步有两个解决方案:

1、接口中调用的方法函数要是异步非阻塞的,配合异步库使用,比如

response1 = yield asynchttpclient.post(url)

response2 = yield asynchttpclient.post(url)

 2、tornado提供excutor,可以将同步函数变为future对象

class TestHandler(BaseHandler):
    __class_name = sys._getframe().f_code.co_name

    def __init__(self, application, request, **kwargs):
        super(ActiveMQListenerHandler, self).__init__(application, request, **kwargs)
        self.conf = options.conf.api.get(self.__class_name)
        self.executor = ThreadPoolExecutor(self.conf.max_thread)  # 用执行时的最大线程数,用于将同步方法变为返回future
    @gen.coroutine
    def post(self):
          print(444444)
          s = yield self.handleTest()
          print(555555)

    #run_on_executor会将下方方法变为future
    @run_on_executor
    def handleTest(self,  *args):
        time.sleep(60)

 

posted @ 2022-01-25 17:30  zipon  阅读(608)  评论(0编辑  收藏  举报