缓冲池内存调整 (影响最大)
# 原来: 256M → 优化: 800M (缓冲池)
innodb_buffer_pool_size = 800M
innodb_buffer_pool_instances = 4 # 2核CPU,增加实例数
连接和并发优化
# 连接数适当增加 (原来500)
max_connections = 800
max_user_connections = 500
# 线程缓存优化
thread_cache_size = 64
其他关键调整
# 临时表和排序优化
tmp_table_size = 32M
max_heap_table_size = 32M
# 缓存优化
table_open_cache = 2048
table_definition_cache = 1024
内存容量调整
# 原来: 1GB → 优化: 2GB
maxmemory 2gb
并发性能优化
# I/O线程数调整 (2核CPU)
io-threads 3 # 原来2,增加到3
io-threads-do-reads yes # 启用I/O线程读取
连接优化
# TCP优化
tcp-backlog 131072 # 原来65535,提升到131072
tcp-keepalive 300 # 原来60,增加到300秒
限流策略调整 (适应新增资源)
# API限流放宽
limit_req_zone $binary_remote_addr zone=api_limit:20m rate=20r/s; # 原来10r/s
# WebSocket限流调整
limit_req_zone $binary_remote_addr zone=ws_limit:20m rate=10r/s; # 原来5r/s
# 连接限制放宽
limit_conn_zone $binary_remote_addr zone=conn_limit:20m;
性能优化
# 工作进程数 (2核CPU)
worker_processes 2; # 明确设置为2
# 连接数优化
worker_connections 4096; # 原来8192,调整为4096更合适
# 缓冲区优化
client_max_body_size 20m; # 原来10m
从单进程uvicorn升级为gunicorn多进程
# 安装gunicorn (如果未安装)
pip install gunicorn
# 修改start_prod.sh启动命令
# 原来: uvicorn单进程
# 优化: gunicorn多进程
gunicorn main:app \
--worker-class uvicorn.workers.UvicornWorker \
--workers 4 \
--bind 0.0.0.0:8766 \
--max-requests 1000 \
--max-requests-jitter 50 \
--access-logfile - \
--log-level info
创建 /etc/sysctl.d/99-lyrria.conf:
# 网络优化
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
# 内存优化
vm.swappiness = 10
vm.dirty_ratio = 20
vm.dirty_background_ratio = 10
# 文件句柄
fs.file-max = 2097152
修改 /etc/security/limits.conf:
* soft nofile 65536
* hard nofile 65536
* soft nproc 65536
* hard nproc 65536
备份当前配置
cp 生产环境配置/my.cnf 生产环境配置/my.cnf.backup
cp 生产环境配置/redis.conf 生产环境配置/redis.conf.backup
cp 生产环境配置/nginx.conf 生产环境配置/nginx.conf.backup
按顺序重启服务 ```bash
cd backend && ./stop_prod.sh
sudo systemctl restart mysqld
sudo systemctl restart redis
sudo systemctl restart nginx
cd backend && ./start_prod.sh ```
验证配置 ```bash
systemctl status mysqld redis nginx
# 检查内存使用 free -h
# 检查连接数 netstat -antp | grep -E ':(3306|6379|80|443|8766)' | wc -l
---
## 7. 监控和调优
### 关键指标监控
**MySQL监控**
```sql
-- 连接数监控
SHOW PROCESSLIST;
-- 缓冲池命中率
SHOW ENGINE INNODB STATUS;
Redis监控
# 内存使用
redis-cli info memory
# 连接数
redis-cli info clients
# 性能统计
redis-cli info stats
系统监控
# CPU使用率
top -b -n1 | head -10
# 内存使用
free -h
# 磁盘I/O
iostat -x 1 5
| 组件 | 优化前 | 优化后 | 提升幅度 |
|---|---|---|---|
| MySQL内存 | 256MB | 800MB | +212% |
| Redis内存 | 1GB | 2GB | +100% |
| API限流 | 10r/s | 20r/s | +100% |
| WS限流 | 5r/s | 10r/s | +100% |
| 后端进程 | 1进程 | 4进程 | +300% |
| 综合并发 | 基准 | - | +150-200% |
最后更新: 2025年12月29日