Gunicorn使用讲解

1.什么是Gunicorn

gunicorn是一个python Wsgi http server,只支持在Unix系统上运行,来源于Ruby的unicorn项目。

Gunicorn使用prefork master-worker模型(在gunicorn中,master被称为arbiter),能够与各种wsgi web框架协作。
Gunicorn是一个WSGI HTTP服务器,python自带的有个web服务器,叫做wsgiref,
Gunicorn的优势在于,它使用了pre-fork worker模式,gunicorn在启动时,会在主进程中预先fork出指定数量的worker进程来处理请求,
gunicorn依靠操作系统来提供负载均衡,推进的worker数量是(2*$num_cores)+1
我们知道,python是单线程的语言,当进程阻塞时,后续请求将排队处理。所用pre-fork worker模式,极大提升了服务器请求负载。

2.gunicorn安装

apt-get install gunicorn
$ pip install greenlet # 使用异步必须安装
$ pip install eventlet # 使用eventlet workers
$ pip install gevent   # 使用gevent workers

3.编写wsgi接口,test.py代码如下

def application(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html')])
    return b'<h1>Hello,web!</h1>'

4.使用gunicorn监听请求,运行以下命令

gunicorn -w 2 -b 0.0.0.0:8000 test.application

运行结果:

-w:指定fork的worker进程数
-b:指定绑定的端口
test:模块名,python文件名
application:变量名,python文件中可调用的wsgi接口名称

5.访问web服务器

和使用wsgiref,访问wsgi接口一致

6.gunicorn相关参数
1)-c CONFIG,--config=CONFIG
指定一个配置文件(py文件)
2)-b BIND,--bind=BIND
与指定socket进行板顶
3)-D,--daemon
后台进程方式运行gunicorn进程
4)-w WORKERS,--workers=WORKERS
工作进程的数量
5)-k WORKERCLASS,--worker-class=WORKERCLASS
工作进程类型,包括sync(默认),eventlet,gevent,tornado,gthread,gaiohttp
6)--backlog INT
最大挂起的连接数
7)--log-level LEVEL
日志输出等级
8)--access-logfile FILE
访问日志输出文件
9)--error-logfile FILE
错误日志输出文件

7.gunicorn参数配置文件
-c CONFIG,--config=CONFIG 指定一个配置文件(py文件)
gunicorn可以写在配置文件中,下面举列说明配置文件的写法,gunicorn.conf.py

bind = "0.0.0.0:8000"
workers = 2

运行以下命令:

gunicorn -c gunicorn.conf.py test:application

运行结果和使用命令行参数,结果一样。

gunicorn配置文件是一个python文件,因此可以实现更复杂的逻辑,如下:

# gunicorn.conf.py
import logging
import logging.handlers
from logging.handlers import WatchedFileHandler
import os
import multiprocessing
bind = '127.0.0.1:8000'      #绑定ip和端口号
backlog = 512                #监听队列
chdir = '/home/test/server/bin'  #gunicorn要切换到的目的工作目录
timeout = 30      #超时
worker_class = 'gevent' #使用gevent模式,还可以使用sync 模式,默认的是sync模式

workers = multiprocessing.cpu_count() * 2 + 1    #进程数
threads = 2 #指定每个进程开启的线程数
loglevel = 'info' #日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'    #设置gunicorn访问日志格式,错误日志无法设置

"""
其每个选项的含义如下:
h          remote address
l          '-'
u          currently '-', may be user name in future releases
t          date of the request
r          status line (e.g. ``GET / HTTP/1.1``)
s          status
b          response length or '-'
f          referer
a          user agent
T          request time in seconds
D          request time in microseconds
L          request time in decimal seconds
p          process ID
"""
accesslog = "/home/test/server/log/gunicorn_access.log"      #访问日志文件
errorlog = "/home/test/server/log/gunicorn_error.log"        #错误日志文件

8.使用ps -ef | grep gunicorn命令找出gunicorn所有进程。
  可使用 kill -9 进程ID 命令来杀掉进程,注意,我们找到主进程杀掉即可,子进程会随之结束。
原文地址:https://www.cnblogs.com/xiaozengzeng/p/14455444.html