参考文档
具体设置参考地址:
https://docs.gunicorn.org/en/stable/settings.html#server-hooks
gunicorn 配置文件(test_gunicorn.py)
#-*- coding:utf-8 -*-
import os
from multiprocessing import cpu_count
def get_next_index(worker_list):
"获取下一个序号"
for i in range(1,workers+1):
if i not in worker_list:
return i
raise Exception("%s"%worker_list)
def pre_fork(server, worker):
if not hasattr(server,"worker_list"):
server.worker_list = []
my_index = get_next_index(server.worker_list)
server.worker_list.append(my_index) #保存到已启动的列表中
worker.my_index = my_index
os.environ["worker_number"] = "%s"%my_index #设置环境变量(工作进程序号)
def child_exit(server, worker):
server.worker_list.remove(worker.my_index) #工作进程退出,从已启动列表中删除
workers = cpu_count()
worker_connections = 2048
backlog = 2048
worker_class = "uvicorn.workers.UvicornWorker"
keepalive = 3
#umask = '002'
daemon = False
bind = '0.0.0.0:9999'
timeout = 1800
pidfile = '/data/run/test_gunicorn.pid'
accesslog = '/data/logs/test_gunicorn/test_gunicorn-access_log'
errorlog = '/data/logs/test_gunicorn/test_gunicorn-error_log'
proc_name = 'mytest'
#reload = True
limit_request_line = 0
limit_request_fields = 32768
limit_request_field_size = 0
threads = 20
应用中获取变量(test_fastapi.py)
#-*- coding:utf-8 -*-
from fastapi import FastAPI
import uvicorn
import setproctitle
import os
print(os.environ["worker_number"]) #获取传递的变量
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.on_event("startup")
async def startup_event():
print("***start***,extra='{extra}'".format(extra = app.extra))
#raise Exception("start_event")
if __name__ == "__main__":
uvicorn.run(app="test_gunicorn_app:app",port=9999,host="0.0.0.0",reload=False,debug=False)
启动
/usr/local/python38/bin/gunicorn -c /etc/supervisor/conf.d/test_gunicorn.py test_fastapi:app
输出:
1
***start***,extra='{}'
2
***start***,extra='{}'
3
4
***start***,extra='{}'
***start***,extra='{}'
其他
设置进程标题(proc_name),需要安装插件
安装:
pip install setproctitle
[xxx@localhost ~]$ ps -ef|grep mytest |grep -v grep
sy 61449 18871 2 11:29 pts/1 00:00:00 gunicorn: master [mytest]
sy 61522 61449 1 11:29 pts/1 00:00:00 gunicorn: worker [mytest]
sy 61532 61449 1 11:29 pts/1 00:00:00 gunicorn: worker [mytest]
sy 61542 61449 1 11:29 pts/1 00:00:00 gunicorn: worker [mytest]
sy 61548 61449 1 11:29 pts/1 00:00:00 gunicorn: worker [mytest]