標籤:設定 ati serve 校正 授權 網站 程式 handler help
測試兩個介面
# -*- coding:utf-8 -*-import timeimport tornado.webimport tornado.genimport tornado.ioloopfrom tornado.concurrent import run_on_executorfrom concurrent.futures import ThreadPoolExecutorclass SyncHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): time.sleep(5) # sleep用來簡單指代某個耗時的io操作 self.write("同步的Hello World")class AsyncHandler(tornado.web.RequestHandler): executor = ThreadPoolExecutor(5) @tornado.gen.coroutine def get(self): resp = yield self.sleep_for_result() self.write(resp) @run_on_executor def sleep_for_result(self): time.sleep(5) return ‘非同步Hello World‘application = tornado.web.Application([ (r‘/sync‘, SyncHandler), (r‘/async‘, AsyncHandler),])if __name__ == "__main__": from tornado.options import options, define define("port", default=8080, help="跑在8080", type=int) http_server = tornado.httpserver.HTTPServer(application) http_server.bind(options.port) http_server.start(1) # 進程數量 tornado.ioloop.IOLoop.instance().start()
啟動tornado服務。
這裡不使用ab測試,使用更靈活的代碼線程池測試效能,使用線程池並發方式請求介面
#coding=utf8import requestsimport timefrom tomorrow import threads@threads(10)def test_sync(): print requests.get(‘http://127.0.0.1:8080/sync‘).content + ‘ ‘ + time.strftime(‘%H:%M:%S‘)@threads(10)def test_async(): print requests.get(‘http://127.0.0.1:8080/async‘).content + ‘ ‘ + time.strftime(‘%H:%M:%S‘)[test_sync() for i in range(100)]#[test_async() for i in range(100)]
同步方式測試如下:
看以看到,10線程請求同步介面時候,是每隔5秒才能領處理完成一個請求。程式中設定的tornado進程是1,如果把tornado服務的進程數量提高為4,每5秒也能處理4個同步請求。
非同步方式測試如下:
看以看到,10線程請求非同步介面時候,是每隔5秒能處理5個請求,因為代碼中設定的ThreadPoolExecutor(5)數量是5。如果設定為8,那麼每5秒可以處理8個請求。
在做聯通 央行徵信基於使用者授權的登入系統時候,需要校正使用者提交的帳號密碼驗證碼,加上使用代理ip時間很不穩定,校正使用者提交的帳號密碼是否能夠登入三方網站時候需要大量時間,就需要使用tornado這種非同步方式了,不然使用者提交帳號密碼後需要很長時間才能得到反饋,使用者體驗就很糟糕。
如果使用django的,使用內建服務,每5秒能處理1個請求,其他的請求都必須等待上一個請求結束,才能被處理。
但django使用uwsgi部署,不會像內建服務表現這麼差,使用uwsgi部署時候一般都會設定進程數量和線程數量,部署後每5秒能處理更多的請求。
。
python tornado非同步效能測試