Gunicorn

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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值