175 lines
4.6 KiB
Python
175 lines
4.6 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
Gunicorn 配置文件 - app_vx.py 生产环境配置
|
||
|
||
使用方式:
|
||
# 方式1: 使用 gevent 异步模式(推荐,支持高并发)
|
||
USE_GEVENT=true gunicorn -c gunicorn_config.py app_vx:app
|
||
|
||
# 方式2: 使用同步多进程模式
|
||
gunicorn -c gunicorn_config.py app_vx:app
|
||
|
||
# 方式3: 使用 systemd 管理(见文件末尾 systemd 配置示例)
|
||
"""
|
||
|
||
import os
|
||
import multiprocessing
|
||
|
||
# ==================== 基础配置 ====================
|
||
|
||
# 绑定地址和端口
|
||
bind = '0.0.0.0:5002'
|
||
|
||
# Worker 进程数(建议:CPU 核心数 * 2 + 1)
|
||
workers = min(multiprocessing.cpu_count() * 2 + 1, 8) # 最多 8 个 worker
|
||
|
||
# Worker 类型
|
||
# - 'sync': 同步模式(默认)
|
||
# - 'gevent': 异步模式(推荐用于 I/O 密集型应用)
|
||
# - 'gthread': 多线程模式
|
||
if os.environ.get('USE_GEVENT', 'false').lower() == 'true':
|
||
worker_class = 'gevent'
|
||
worker_connections = 1000 # gevent 模式下每个 worker 的最大并发连接数
|
||
else:
|
||
worker_class = 'gthread'
|
||
threads = 4 # gthread 模式下每个 worker 的线程数
|
||
|
||
# 每个 worker 处理的最大请求数,超过后重启(防止内存泄漏)
|
||
max_requests = 10000
|
||
max_requests_jitter = 1000 # 随机抖动,避免所有 worker 同时重启
|
||
|
||
# ==================== 超时配置 ====================
|
||
|
||
# Worker 超时时间(秒),超过后 worker 会被杀死重启
|
||
timeout = 120
|
||
|
||
# 优雅关闭超时时间(秒)
|
||
graceful_timeout = 30
|
||
|
||
# 保持连接超时时间(秒)
|
||
keepalive = 5
|
||
|
||
# ==================== SSL 配置 ====================
|
||
|
||
# SSL 证书路径(生产环境需要配置)
|
||
cert_file = '/etc/letsencrypt/live/api.valuefrontier.cn/fullchain.pem'
|
||
key_file = '/etc/letsencrypt/live/api.valuefrontier.cn/privkey.pem'
|
||
|
||
if os.path.exists(cert_file) and os.path.exists(key_file):
|
||
certfile = cert_file
|
||
keyfile = key_file
|
||
|
||
# ==================== 日志配置 ====================
|
||
|
||
# 访问日志文件路径(- 表示输出到 stdout)
|
||
accesslog = '-'
|
||
|
||
# 错误日志文件路径(- 表示输出到 stderr)
|
||
errorlog = '-'
|
||
|
||
# 日志级别:debug, info, warning, error, critical
|
||
loglevel = 'info'
|
||
|
||
# 访问日志格式
|
||
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s'
|
||
|
||
# ==================== 进程管理 ====================
|
||
|
||
# 是否在后台运行(daemon 模式)
|
||
daemon = False
|
||
|
||
# PID 文件路径
|
||
pidfile = '/tmp/gunicorn_app_vx.pid'
|
||
|
||
# 进程名称
|
||
proc_name = 'app_vx'
|
||
|
||
# ==================== 预加载配置 ====================
|
||
|
||
# 是否预加载应用代码(可以减少内存占用,但会增加启动时间)
|
||
preload_app = True
|
||
|
||
# ==================== Hook 函数 ====================
|
||
|
||
def on_starting(server):
|
||
"""服务器启动时调用"""
|
||
print(f"Gunicorn 服务器正在启动...")
|
||
print(f" Workers: {server.app.cfg.workers}")
|
||
print(f" Worker Class: {server.app.cfg.worker_class}")
|
||
print(f" Bind: {server.app.cfg.bind}")
|
||
|
||
|
||
def when_ready(server):
|
||
"""服务准备就绪时调用,初始化缓存"""
|
||
print("Gunicorn 服务准备就绪,开始初始化...")
|
||
from app_vx import app, init_sywg_industry_cache
|
||
with app.app_context():
|
||
init_sywg_industry_cache()
|
||
print("初始化完成!")
|
||
|
||
|
||
def on_reload(server):
|
||
"""服务器重载时调用"""
|
||
print("Gunicorn 服务器正在重载...")
|
||
|
||
|
||
def worker_int(worker):
|
||
"""Worker 收到 INT 或 QUIT 信号时调用"""
|
||
print(f"Worker {worker.pid} 收到中断信号")
|
||
|
||
|
||
def worker_abort(worker):
|
||
"""Worker 收到 SIGABRT 信号时调用(超时)"""
|
||
print(f"Worker {worker.pid} 超时被终止")
|
||
|
||
|
||
def post_fork(server, worker):
|
||
"""Worker 进程 fork 之后调用"""
|
||
print(f"Worker {worker.pid} 已启动")
|
||
|
||
|
||
def worker_exit(server, worker):
|
||
"""Worker 退出时调用"""
|
||
print(f"Worker {worker.pid} 已退出")
|
||
|
||
|
||
def on_exit(server):
|
||
"""服务器退出时调用"""
|
||
print("Gunicorn 服务器已关闭")
|
||
|
||
|
||
# ==================== systemd 配置示例 ====================
|
||
"""
|
||
将以下内容保存为 /etc/systemd/system/app_vx.service:
|
||
|
||
[Unit]
|
||
Description=Gunicorn instance to serve app_vx
|
||
After=network.target
|
||
|
||
[Service]
|
||
User=www-data
|
||
Group=www-data
|
||
WorkingDirectory=/path/to/vf_react
|
||
Environment="PATH=/path/to/venv/bin"
|
||
Environment="USE_GEVENT=true"
|
||
ExecStart=/path/to/venv/bin/gunicorn -c gunicorn_config.py app_vx:app
|
||
ExecReload=/bin/kill -s HUP $MAINPID
|
||
KillMode=mixed
|
||
TimeoutStopSec=5
|
||
PrivateTmp=true
|
||
Restart=always
|
||
RestartSec=10
|
||
|
||
[Install]
|
||
WantedBy=multi-user.target
|
||
|
||
启用服务:
|
||
sudo systemctl daemon-reload
|
||
sudo systemctl enable app_vx
|
||
sudo systemctl start app_vx
|
||
sudo systemctl status app_vx
|
||
|
||
查看日志:
|
||
sudo journalctl -u app_vx -f
|
||
"""
|