【无标题】

tornado 单线程异步,避免阻塞其他请求

描述

tornado基于 epoll 的事件驱动框架,单线程的。
在处理耗时操作时,如sleep或者网络io的时候会则阻塞整个系统,让其他请求无法执行

耗时操作

  1. time.sleep(10)
  2. request.get() #耗时的http请求

解决办法

睡眠操作

time.sleep(10)  # 阻塞系统
yield tornado.gen.sleep(5)  不阻塞系统

耗时网络请求

requests.post(url, headers=headers, timeout=timeout, data=sql)  # 阻塞系统
#  不阻塞系统。 等待网络请求的完成,但不阻塞其他的请求操作
 client = tornado.httpclient.AsyncHTTPClient()
    result = yield client.fetch(url, method='POST', headers=headers, body=sql, connect_timeout=timeout)

异步整个方法 通过tornado的@run_on_executor解释器异步整个方法


class xxHandler():
    executor = ThreadPoolExecutor(10)

    @run_on_executor
    def long_time_wait(self):
        pass

    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
        yield self.long_time_wait()
        

参考资料

https://blog.csdn.net/u012089823/article/details/88244884
https://zhuanlan.zhihu.com/p/507224519

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值