Python代码
p.py
fromflaskimportFlask, jsonifyfromsqlalchemyimportcreate_enginefromsqlalchemy.poolimportQueuePoolapp=Flask(__name__) engine=create_engine(url="mysql+pymysql://root:123456@172.16.5.9:3306/demo?charset=utf8", pool_size=20, pool_recycle=3600*7, poolclass=QueuePool, echo=False) defto_json(item): return { "id": item[0], "username": item[1], "email": item[2] } route("/", methods=["get"]) .defindex(): data= {"msg": "", "data": []} withengine.connect() asconnect: result=connect.execute("select id,username,email from user") foriteminresult.all(): data["data"].append(to_json(item)) returnjsonify(data), 200if__name__=="__main__": app.run(host="0.0.0.0", port=7002)
NGINX配置
upstreambackend { server 172.16.5.9:7002; } server { listen 17002; location / { proxy_passhttp://backend; } }
架构图
flask直接运行,gunicon运行flask,两者是只有一个在运行,不是同时运行
运行程序
[root@izbp152ke14timzud0du15zpool]# python3 p.py*ServingFlaskapp'p' (lazyloading) *Environment: productionWARNING: Thisisadevelopmentserver. Donotuseitinaproductiondeployment. UseaproductionWSGIserverinstead. *Debugmode: off*Runningonalladdresses. WARNING: Thisisadevelopmentserver. Donotuseitinaproductiondeployment. *Runningonhttp://172.16.5.9:7002/ (PressCTRL+Ctoquit)
服务端负载,CPU为4核的,资源使用率5分之1吧
样本60万请求数,tps为492/sec,p90为1303ms
通过gunicorn来运行flask应用
[root@izbp152ke14timzud0du15zpool]# gunicorn -w 8 -b 172.16.5.9:7002 p:app[2021-11-0620:14:21+0800] [19426] [INFO] Startinggunicorn20.1.0[2021-11-0620:14:21+0800] [19426] [INFO] Listeningat: http://172.16.5.9:7002 (19426) [2021-11-0620:14:21+0800] [19426] [INFO] Usingworker: sync[2021-11-0620:14:21+0800] [19429] [INFO] Bootingworkerwithpid: 19429[2021-11-0620:14:21+0800] [19449] [INFO] Bootingworkerwithpid: 19449[2021-11-0620:14:21+0800] [19486] [INFO] Bootingworkerwithpid: 19486[2021-11-0620:14:21+0800] [19504] [INFO] Bootingworkerwithpid: 19504[2021-11-0620:14:21+0800] [19507] [INFO] Bootingworkerwithpid: 19507[2021-11-0620:14:21+0800] [19508] [INFO] Bootingworkerwithpid: 19508[2021-11-0620:14:21+0800] [19509] [INFO] Bootingworkerwithpid: 19509[2021-11-0620:14:21+0800] [19511] [INFO] Bootingworkerwithpid: 19511
服务端负载,基本上已经满负载了
样本60万请求数,tps为1939/sec,p99为1114ms
在4核CPU的情况下,同环境,不同方式运行应用,tps吞吐量提示将近4倍
结论:
通过直接运行flask,多核CPU无法充分利用资源,性能低下
通过gunicorn运行flask,多核CPU可以充分利用,性能高效