1.什么是Gunicorn
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
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" #錯誤日志文件