gunicorn 主进程传递序号到子进程

参考文档

具体设置参考地址:
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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值