python+flask+gunicorn(gevent模式)+supervisor搭建图像识别服务

本篇文章是对之前一篇文章的续写,识别部分的代码python使用Flask框架搭建图像识别服务,这里就不重复CV了
引入了gunicorn协程工作模式和supervisor来做并发和服务进程的管理,还是以图像识别这个代码为例来做补充。环境是Ubuntu18.04。

copy一段,Gunicorn 绿色独角兽是一个 Python WSGI UNIX 的 HTTP 服务器。这是一个 pre-fork worker 的模型,从 Ruby 的独角兽(Unicorn )项目移植。该 Gunicorn 服务器大致与各种 Web 框架兼容,只需非常简单的执行,轻量级的资源消耗,以及相当迅速。
安装:pip install gunicorn gevent
在项目目录下新建config.py代码作为gunicorn的配置文件
代码如下:

config.py
import os
import gevent.monkey
gevent.monkey.patch_all()
import multiprocessing

debug = False
loglevel = 'debug'
bind = "0.0.0.0:8091"  # 我这里是绑定一个8091端口
在当前目录下创建一个log文件夹用来存放日志和运行的pid
if not os.path.exists('./logs'):
    os.mkdir('./logs')
pidfile = "logs/gunicorn.pid"  # ID号
accesslog = "logs/access.log"  # 请求日志的记录
errorlog = "logs/debug.log"
daemon = False  # 守护模式为False,如果启动有异常等报错会显示出来,True则不会显示需要查看日志
timeout = 120  # 超时时间
workers = multiprocessing.cpu_count() * 2 + 1  # 进程数
worker_class = 'gevent'  # 工作模式
x_forwarded_for_header = 'X-FORWARDED-FOR'

workers进程数设置多少合适用gunicorn官网一句话:
A positive integer generally in the 2-4 x $(NUM_CORES) range. You’ll want to vary this a bit to find the best for your particular application’s work load.

threads每个进程的线程数,我上面没写,因为
A positive integer generally in the 2-4 x $(NUM_CORES) range. You’ll want to vary this a bit to find the best for your particular application’s work load.

If it is not defined, the default is 1.

This setting only affects the Gthread worker type.

安装:sudo apt install supervisor
安装后在/etc/supervisor/conf.d下建立一个recognition.conf文件,如果要管理多个服务可以建立多个文件,recognition.conf命令如下

[program:recognition]
startsecs=1  # 启动1秒后没有异常退出,表示正常
command=/home/wmj/anaconda3/bin/gunicorn -c config.py myweb:app  # 用自己的gunicorn路径
directory=/home/wmj/recognition  # 整个项目的绝对路径
user=root  # 用户身份,只能在root下执行
autostart=true  # supervisord启动时候自动启动,开机自启动
autorestart=true  #  程序退出后自动重启
startretires=3  # 启动失败重试次数
stopasgroup=true  # 进程被杀死时,是否向这个进程组发送stop信号

注意一点:当使用supervisor时候gunicorn的配置文件config.py中daemon=False,否则会报错。
保存配置文件之后进入root模式
1、supervisorctl update 更新配置文件
2、supervisorctl start recognition 启动识别服务的进程
启动后可以查看服务是否启动 supervisorctl status,也可以查看gunicorn是否启动 ps -ef|grep gunicorn

载入最新配置,服务不会中断:supervisorctl reload
停止服务: supervisorctl stop recognition
到此整个识别服务就完成了。

Original: https://blog.csdn.net/Y_snower/article/details/126226693
Author: 程序鱼鱼mj
Title: python+flask+gunicorn(gevent模式)+supervisor搭建图像识别服务

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/645482/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球