初学python-tornado关于同一个接口同时访问的并发问题

飞喵 2019-09-24 04:08:00
python,tornado,搭建了一个简单的web接口服务

但是发现,接口之间相互阻塞,一个接口被访问,只有结束后,其他接口的访问才能进来

于是按照网上的讲解,加入了
@tornado.web.asynchronous
@tornado.gen.coroutine
使用yield 执行 @run_on_executor的方法

每个接口都这样做后,接口之间不再相互阻塞


但是问题是,即使使用了异步修饰符,对于同一个接口,多个访问时,还是会同步执行,无法并发。

比如A接口已经实现上面的异步修饰,A里面sleep 10秒,连续两次访问,第二次只有等第一次结束时(10秒后),才会进入。

搜了好久也没有找到原因,请各位帮忙解答



application = tornado.web.Application([
(r"/test1", test1_handler.test1),
(r"/test2", test2_handler.test2),
])

if __name__ == "__main__":
application.listen(8291)
tornado.ioloop.IOLoop.instance().start()


import logging
import time
from concurrent.futures import ThreadPoolExecutor

import tornado
import tornado.web
import tornado.gen
from tornado.concurrent import run_on_executor
from common.executor_handler import ExecutorInstance


class test2(tornado.web.RequestHandler):
# executor = ExecutorInstance()
executor = ThreadPoolExecutor(4)

@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
yield self.wait(5)

@run_on_executor
def wait(self,s):
tag = time.time()
logging.info("test2 开始 %s" % tag)
time.sleep(s)
self.write("success")
logging.info("test2 结束 %s" % tag)
self.finish()



如上,连续两次执行接口欧test2时,结果如下:

2019-09-24 16:07:15,013 - root - INFO - test2 开始 1569312435.013742
2019-09-24 16:07:20,019 - root - INFO - test2 结束 1569312435.013742
2019-09-24 16:07:20,021 - tornado.access - INFO - 304 GET /test2 (127.0.0.1) 5017.06ms
2019-09-24 16:07:20,025 - root - INFO - test2 开始 1569312440.024935
2019-09-24 16:07:25,027 - root - INFO - test2 结束 1569312440.024935
2019-09-24 16:07:25,028 - tornado.access - INFO - 304 GET /test2 (127.0.0.1) 5004.62ms

可以看到第二次执行等待第一次结束才开始,请问是为什么,怎么解决,否则没有任何并发可言啊
...全文
732 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
liyzh_inspur 2020-12-21
  • 打赏
  • 举报
回复
from tornado.concurrent import run_on_executor from concurrent.futures import ThreadPoolExecutor import tornado from tornado import gen import tornado.web import time class TestHandler(tornado.web.RequestHandler): executor = ThreadPoolExecutor(2) @gen.coroutine def get(self): result = yield self.doingRunTask() self.write(result) @run_on_executor def doingRunTask(self): print('start') time.sleep(5) print('end') return 'ddddddddddd' application = tornado.web.Application([ (r"/test", TestHandler), ]) if __name__ == "__main__": application.listen(8000) tornado.ioloop.IOLoop.instance().start()
liyzh_inspur 2020-12-21
  • 打赏
  • 举报
回复
必须用两个浏览器(或者两台机器)打开请求,才能看出来并发,在一个浏览器中打开,两个tab也都不行
飞喵 2019-09-25
  • 打赏
  • 举报
回复
333333
飞喵 2019-09-25
  • 打赏
  • 举报
回复
111111
飞喵 2019-09-24
  • 打赏
  • 举报
回复
有人知道吗,给个搜索方向也行啊

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧