Gunicorn, 一個支持WSGI協議的web服務器
Flask, 一個輕量級的python web框架
Gunicorn目前自帶支持幾種工作方式:
sync (默認值)
eventlet
gevent
tornado
測試環境准備
python 2.7+
redis-server 2.8.4
壓力測試工具ab
代碼及相關python包准備 創建虛一個新的虛擬環境並安裝需要的包
$ mkvirtualenv test
$ workon test
$ cat requirements.txt
gunicorn==19.3.0
flask==0.10.1
flask-redis==0.1.0
gevent==1.0.2
tornado==4.2
eventlet==0.17.4
$ pip install -r requirements.txt
測試程序app.py
:::python
from flask import Flask
from flask_redis import FlaskRedis
REDIS_URL = "redis://:password-string@localhost:6379/0"
app = Flask(__name__)
app.config.from_object(__name__)
redis = FlaskRedis(app, True)
@app.route("/")
def index():
redis.incr("hit", 1)
return redis.get("hit")
if __name__ == '__main__':
app.run()
開始測試
使用ab工具,並行500個客戶端, 發送50000次請求
$ ab -c 500 -t 30 -r "http://127.0.0.1:8000/"
分別使用四種方式啟動使用服務, 並開啟4個worker
$ gunicorn -w 4 app:app --error-logfile - --worker-class sync
$ gunicorn -w 4 app:app --error-logfile - --worker-class gevent
$ gunicorn -w 4 app:app --error-logfile - --worker-class tornado
$ gunicorn -w 4 app:app --error-logfile - --worker-class eventlet
結果比較
Worker class Time taken for tests Complete requests Failed requests Requests per second 用戶平均請求等待時間 服務器平均處理時間 最小連接時間 平均連接時間 50%的連接時間 最大連接時間
sync 37.363 s 49928 793 1336.29 374.169 ms 0.748 ms 5 ms 75 ms 17 ms 31746 ms
tornado 13.995 50000 543 3572.64 139.953 ms 0.280 ms 6 ms 110 ms 24 ms 13837 ms
eventlet 8.156 50000 0 6130.74 81.556 0.163 ms 2 ms 80 ms 62 ms 3153 ms
gevent 7.647 s 50000 0 6538.23 76.473 ms 0.153 ms 1 ms 74 ms 52 ms 1122 ms
從測試結果來看,默認自帶sync效率很低,並且在測試時發現,采用sync方式在高並發時 會出現woker重啟的情況, 如下:
[2015-06-25 11:31:06 +0000] [27040] [CRITICAL] WORKER TIMEOUT (pid:27064)
[2015-06-25 11:31:06 +0000] [27040] [CRITICAL] WORKER TIMEOUT (pid:27051)
[2015-06-25 11:31:06 +0000] [27040] [CRITICAL] WORKER TIMEOUT (pid:27045)
[2015-06-25 11:31:06 +0000] [27040] [CRITICAL] WORKER TIMEOUT (pid:27046)
[2015-06-25 11:31:06 +0000] [27064] [INFO] Worker exiting (pid: 27064)
[2015-06-25 11:31:06 +0000] [27051] [INFO] Worker exiting (pid: 27051)
[2015-06-25 11:31:06 +0000] [27045] [INFO] Worker exiting (pid: 27045)
[2015-06-25 11:31:06 +0000] [27046] [INFO] Worker exiting (pid: 27046)
[2015-06-25 11:31:06 +0000] [27263] [INFO] Booting worker with pid: 27263
[2015-06-25 11:31:06 +0000] [27264] [INFO] Booting worker with pid: 27264
[2015-06-25 11:31:06 +0000] [27277] [INFO] Booting worker with pid: 27277
[2015-06-25 11:31:06 +0000] [27280] [INFO] Booting worker with pid: 27280
eventlet 和gevent兩種方式效果最好,數據基本差不多.
文章作者 crazygit
