tornado,这个python的web框架,官网介绍说,支持高并发,每秒可以处理数以千计的连接。
但,很多人初次用,coding下来也很爽,公司业务流量很小,毫无发觉哪里代码写的不对。
代码是这样子的:
import tornado.web as tw
from densenet_demo import OcrPredictController
import tornado.ioloop as ti
def make_app():
app = tw.Application([(r'/ocr', OcrPredictController)])
return app
if __name__ == '__main__':
app = make_app()
port = 8882
app.listen(port)
ti.IOLoop.current().start()
OcrPredictController写成这样子的:
import time
import urllib.request
from hjocr import request
import tornado
from tornado import gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
class OcrPredictController(tornado.web.RequestHandler):
def post(self):
print('-------------------------------1-------------------------------------')
b = yield self.runCode()
print(b)
self.finish(b)
def runCode(self):
print('--------------------------------2----------------------------------------')
for i in range(500):
for j in range(1000):
for k in range(1000):
a = 1
return "{'offers': []}"
直到有一次,高并发像狼一样,真的来了。。。
结果你想到了,慢,非常慢,阻的死死的
为什么
因为你代码写成同步的了
你觉得,tornado号称模式是非阻塞式服务器,但是代码还是被阻塞了?
不,你可能混淆了 阻塞/非阻塞 同步/异步。
tornado, 非阻塞式,没错。10个请求同时进行,tornado处理第一个请求时,并没有拒绝你后9个请求。后9个请求在排队,老长的队,一个一个检票。
要写出异步的代码,你得用它的异步库,这里推荐协程(也可以用回调函数处理异步)
协程: @tornado.gen.coroutine 和 yield
代码如下:
import time
import urllib.request
from hjocr import request
import tornado
from tornado import gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
class OcrPredictController(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(2)
@gen.coroutine
def post(self):
print('----------------------------------------1-----------------------------------------')
b = yield self.runCode()
print(b)
self.finish(b)
@gen.coroutine
@run_on_executor
def runCode(self):
print('-----------------------------------2----------------------------------------------')
for i in range(500):
for j in range(1000):
for k in range(1000):
a = 1
return "{'offers': []}"
我的版本:python 3.6
tornado:4.4