【gunicorn】gunicorn基本使用

Gunicorn

gunicorn是一个基于python的Web Servers Gateway Interface for unix; 就是web 服务器端接收请求和python app 应用的一个桥梁;
如果不用gunicorn,只是使用Flask,对于大量和同时的请求,就会奔溃和出现错误;而gunicorn就是对于大量高并发的请求,能够实现请求到达服务器,以及作出相应,并能根据负载需求,及时增大/减少worker,做到管理协调的作用。

基本介绍

gunicorn是启动app程序的一种方式,不同于直接在main文件中启动app程序,这样更方便与管理;
三种启动方式:

  • workers模式

    每个worker都是一个加载python应用程序的UNIX进程 worker之间没有共享内存

    建议workers 数量是 (2*CPU) + 1;

  • 多线程模式

    gunicorn 还允许每个worker拥有多个线程,在这种模式下,每个worker都会加载一次,同一个worker生成的每个线程共享相同的内存空间,使用threads模式,每一次使用threads模式,worker类就会是gthread;

    gunicorn -w 5 --threads=2  main:app
    #等同于
    gunicorn -w 5 --thread=2 --worker-class=gthread main:app
    
  • 伪线程 gevent (协程)

    gunicorn --worker-class=gevent --worker-connections=1000 -w 3 main:app
    

    work-connections 是对gevent worker类的特殊设置;建议workers数量仍然是 (2*CPU) + 1;

    在这种情况下,最大的并发请求数 是3000(3个worker * 1000连接/worker).

基本使用

使用配置文件方式启动

gunicorn --config=config.py myapp.test:app
#myapp.test为文件,第二个指的是flask应用的名字;

关闭gunicorn

pstree -ap|grep gunicorn #寻找masterpid
kill -HUP 9479 #重启Gunicorn任务
kill -9 9479 #退出gunicorn任务
  • gunicorn address used
    如使用gunicorn启动,即不使用mian启动,不需要在使用app.run();
#gunicorn 启动
if __name__ != '__main__':
	#日志的绑定
	gunicorn_logger = logging.getLogger(‘gunicorn.error’)#获得gunicorn的logger
	#将gunicorn的logger和flask app的logger绑定在一起
    app.logger.handlers = gunicorn_logger.handlers
    #将绑定的logger 的level设置成gunicorn logger的level, 因为最终输出的log level是在gunicorn中配置的
    app.logger.setLevel(gunicorn_logger.level)
    #启动分析任务
    crossline_t = threading.Thread(target=crossline_analyze.task_start)
    crossline_t.start()
  • 退出gunicorn
    根据pid文件中的pid号,来进行进程结束
    kill -QUIT pid
    kill -TERM pid	
    

ref:

gunicorn 配置文件
gunicorn 文档
Gunicorn介绍与压测
gunicorn日志绑定
参考01
pid文件的作用

常见错误

  • No module named <module_name>" while running gunicorn
    在gunicorn中无法找到celery,通过查看which gunicorn可知默认调用的是local下的gunicorn;卸载重新在安装了celery的虚拟环境下安装gunicorn;
    在使用时,需要指明gunicorn在虚拟环境下的具体位置;
    若出现bad interpreter错误,需要进行bin/gunicorn中,编辑首行的python解释器路径;
    将虚拟环境下的gunicorn软链接至local路径下,则使用时无须指明具体路径;

  • gunicorn.errors.HaltServer
    在启动时加上--preload可显示具体错误;

猜你喜欢

转载自blog.csdn.net/lishijin5421/article/details/127674812
今日推荐