前言:
使用flask做服务时,可以使用python run.py的方式运行,但是这样不能用于生产环境,可能会出现连接无响应的情况。后来通过查找资料,发现flask服务处理多线程、高并发的一下方法,主要有一下几个方面:
1.通过设置app.run()的参数,来达到多线程的效果,具体参数:
# 1.threaded : 多线程支持,默认为False,即不开启多线程; app.run(threaded=True) # 2.processes:进程数量,默认为1. app.run(processes=True) ps:多进程或多线程只能选择一个,不能同时开启
2.使用genvent做协程,解决高并发:
from genvent.wsgi import WSGIServer from genvent import monkey monkey.patch_all() app = Flask(__name__) app.config.from_object(config) api = Api(app) db = DBInfo() # db_old = DBInfo_old()
然后通过这种方式包装WSGIServer((address,port), app).serve_forever()
通过python code.py 的方法,来启动服务
3.通过Guicorn(with genvent)的形式来对app进行包装,来启动服务;
通过一下代码,来启动项目
# 启动命令
gunicorn -c gun.py thread_explore:app
其中gun.py是gunicorn的配置文件
thread_explore是服务的主程序
app是flask的app
gun.py的具体内容:
import os import gevent.monkey gevent.monkey.patch_all() import multiprocessing # 服务地址(adderes:port) bind = 127.0.0.1;5000 # 启动进程数量 workers = multiprocessing.cpu_count() * 2 +1 worker_class = 'gevent' threads = 20 preload_app = True reload = True x_forwarded_for_header = 'X_FORWARDED-FOR'
ps:这里启动进程数量应该是根据CPU个数来确定的,最好是2 * CPU数 + 1
参考资料:
https://www.jianshu.com/p/a90775e33b52
https://www.cnblogs.com/lesliexong/p/9396850.html
作者:sunshaoping1994
链接:https://www.jianshu.com/p/79489cfc6fb9