1. 简介
1.1 定义
- Gunicorn(绿色独角兽)是一个遵循Python WSGI协议的HTTP服务器。从Ruby的独角兽(Unicorn )项目移植。
1.2 特点
- 该Gunicorn服务器与各种Web框架兼容,实现非常简单,轻量级的资源消耗。
- Gunicorn直接用命令启动,不需要编写配置文件,相对uWSGI要容易很多。
2. 使用
2.1 安装gunicorn
pip install gunicorn
2.2 查看命令行选项
- 安装gunicorn成功后,通过命令行的方式可以查看gunicorn的使用信息。
$ gunicorn -h
2.3 直接运行
#直接运行,默认启动的127.0.0.1::8000
gunicorn 运行文件名称:Flask程序实例名
2.4 指定进程和端口号
-w
: 表示进程(worker)
-b
:表示绑定ip地址和端口号(bind)
-threads
或-t
:多线程
-k
:协程,异步方案
# 使用gevent做异步(默认worker是同步的) 多进程+协程
gunicorn -w 8 --bind 0.0.0.0:8000 -k 'gevent' 运行文件名称:Flask程序实例名
# 使用gunicorn命令启动flask项目
# -w 8
8个进程
# --bind 0.0.0.0:8000
ip + 端口
# -k 'gevent'
协程
3. 应用
Gunicorn是轻量级服务器,一般与轻量级框架Flask一起使用
3.1 Flask+Gunicorn+Gevent
实现高并发
新建配置文件:gunicorn_config.py
# 多进程
import multiprocessing
"""gunicor+gevent 的配置文件"""
# 预加载资源(占位图片,缓存数据)
preload_app = True
# 绑定 ip + 端口
blind = "0.0.0.0:5000"
# 进程数 = cpu数量 * 2 +1
workers = multiprocessing.cpu_count() * 2 + 1
# 线程数 = cpu 数量 * 2
threads = multiprocessing.cpu_count() * 2
# 等待对垒最大长度,超过这个长度的链接被拒绝
backlog = 2048 # 队列
# 工作模式--协程
worker_class = "gevent"
# 最大客户客户端并发数量,对使用线程和协程的worker的工作有影响
# 服务器配置设置的值 1200:中小型项目 上万并发:中大型
# 服务器硬件:宽带+数据库+内存
# 服务器的架构:集群 主从
worker_connections = 1200
# 进程名称
proc_name = 'gunicorn.pid'
# 进程pid记录文件
pidfile = 'app_run.log'
# 日志等级
loglevel = 'debug'
# 日志文件名
logfile = 'debug.log'
# 访问记录
access_log_format = '%(h)s %(t)s %(u)s %(q)s'
# 运行方式 命令行
gunicorn -c gunicorn_config.py flask_server:app
3.2 与meinheld高并发
- meinheld:数据结构发生改变,堆发生改变
安装meinheld:
pip install meinheld
import multiprocessing
"""guicorn+meinheld 的配置文件"""
# 预加载资源
preload_app = True
# 绑定
blind = "0.0.0.0:5000"
# 进程数:cpu数量 * 2 +1
workers = multiprocessing.cpu_count() * 2 + 1
# 线程数: cpu数量 * 2
threads = multiprocessing.cpu_count() * 2
# 等待队列最大长度,超过这个长度的链接将拒绝连接
backlog = 2048
# 工作模式
work_class = "egg:meinheld# gunicorn_worker"
# 最大客户客户端并发数量,对使用线程和协程的worker的工作有影响
worker_connections = 1200
# 进程名称
proc_name = 'gunicorn.pid'
# 进程pid记录文件
pidfile = 'app_run.log'
# 日志等级
loglevel = 'debug'
# 日志文件名
logfile = 'debug.log'
# 访问记录
accesslog = 'access.log'
# 访问记录格式
access_log_format = '%(h)s %(t)s %(u)s %(q)s'
# 运行方式 命令行
gunicorn -c gunicorn_config.py flask_server:app