• 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)
  • 相关阅读:
    WPF一步一脚印系列(1):万事起头难
    php设置时区
    关于我的几个博客
    php如何实现页面跳转
    穷人与富人的区别
    如何抓取关键字在百度搜索的排名
    我的博客园开通了
    在Foxmail中出现SSL连接错误应该如何解决
    javascript实现键盘按下回车时触发
    关于网站分页
  • 原文地址:https://www.cnblogs.com/zipon/p/15843819.html
Copyright © 2020-2023  润新知