zlwu 10 ماه پیش
والد
کامیت
e32d195db3

+ 29 - 12
backend/start_prod.sh

@@ -52,6 +52,12 @@ if ! python3 -c "import fastapi" &> /dev/null; then
     pip install -r requirements.txt
     pip install -r requirements.txt
 fi
 fi
 
 
+# 检查 gunicorn 是否已安装
+if ! command -v gunicorn &> /dev/null; then
+    echo -e "${YELLOW}⚠️  警告: 未检测到 gunicorn,正在安装...${NC}"
+    pip install gunicorn
+fi
+
 # 设置环境变量,指定使用 .env.lyrria
 # 设置环境变量,指定使用 .env.lyrria
 export ENV_FILE=".env.lyrria"
 export ENV_FILE=".env.lyrria"
 
 
@@ -78,18 +84,29 @@ echo -e "${YELLOW}环境文件: $ENV_FILE${NC}"
 echo -e "${YELLOW}工作目录: $SCRIPT_DIR${NC}"
 echo -e "${YELLOW}工作目录: $SCRIPT_DIR${NC}"
 echo ""
 echo ""
 
 
-# 使用 uvicorn 启动(生产环境建议使用 gunicorn + uvicorn workers)
-# 如果已安装 gunicorn,可以使用以下命令:
-# nohup gunicorn main:app --worker-class uvicorn.workers.UvicornWorker --workers 4 --bind 0.0.0.0:8766 > backend_nohup.log 2>&1 &
-
-# 直接使用 uvicorn 启动(适合单进程或小规模部署)
-nohup python3 -m uvicorn main:app \
-    --host 0.0.0.0 \
-    --port 8766 \
-    --workers 1 \
-    --no-access-log \
-    --log-level info \
-    > backend_nohup.log 2>&1 &
+# 尝试使用 gunicorn 多进程模式(2核4G优化配置)
+if command -v gunicorn &> /dev/null && python3 -c "import uvicorn.workers" &> /dev/null; then
+    echo -e "${GREEN}✅ 使用 gunicorn 多进程模式(4个worker)...${NC}"
+    nohup 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 \
+        > backend_nohup.log 2>&1 &
+else
+    echo -e "${YELLOW}⚠️  gunicorn 或 uvicorn-worker 不支持,回退到 uvicorn 单进程模式...${NC}"
+    # 回退到 uvicorn 单进程模式
+    nohup python3 -m uvicorn main:app \
+        --host 0.0.0.0 \
+        --port 8766 \
+        --workers 1 \
+        --no-access-log \
+        --log-level info \
+        > backend_nohup.log 2>&1 &
+fi
 
 
 BACKEND_PID=$!
 BACKEND_PID=$!
 echo $BACKEND_PID > "$PID_FILE"
 echo $BACKEND_PID > "$PID_FILE"

+ 103 - 0
backend/start_prod.sh.backup

@@ -0,0 +1,103 @@
+#!/bin/bash
+
+# 生产环境启动脚本
+# 使用 .env.lyrria 作为环境配置文件
+
+set -e  # 遇到错误立即退出
+
+# 获取脚本所在目录(backend 目录)
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+cd "$SCRIPT_DIR"
+
+# 颜色输出
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+RED='\033[0;31m'
+NC='\033[0m' # No Color
+
+echo -e "${GREEN}🚀 启动 Lyrria 生产环境服务...${NC}"
+
+# 检查 .env.lyrria 文件是否存在
+ENV_FILE="$SCRIPT_DIR/.env.lyrria"
+if [ ! -f "$ENV_FILE" ]; then
+    echo -e "${RED}❌ 错误: 未找到环境配置文件 $ENV_FILE${NC}"
+    echo -e "${YELLOW}提示: 请确保 .env.lyrria 文件存在于 backend 目录${NC}"
+    exit 1
+fi
+
+echo -e "${GREEN}✅ 找到环境配置文件: $ENV_FILE${NC}"
+
+# 检查 Python 环境
+if ! command -v python3 &> /dev/null; then
+    echo -e "${RED}❌ 错误: 未找到 python3 命令${NC}"
+    exit 1
+fi
+
+# 检查虚拟环境(可选,如果使用虚拟环境)
+if [ -d "venv" ] || [ -d ".venv" ]; then
+    VENV_DIR=""
+    if [ -d "venv" ]; then
+        VENV_DIR="venv"
+    else
+        VENV_DIR=".venv"
+    fi
+    
+    echo -e "${GREEN}✅ 激活虚拟环境: $VENV_DIR${NC}"
+    source "$VENV_DIR/bin/activate"
+fi
+
+# 检查依赖是否已安装
+if ! python3 -c "import fastapi" &> /dev/null; then
+    echo -e "${YELLOW}⚠️  警告: 未检测到 FastAPI,正在安装依赖...${NC}"
+    pip install -r requirements.txt
+fi
+
+# 设置环境变量,指定使用 .env.lyrria
+export ENV_FILE=".env.lyrria"
+
+# 设置生产环境标志
+export DEBUG="false"
+
+# 检查服务是否已在运行
+PID_FILE="$SCRIPT_DIR/backend.pid"
+if [ -f "$PID_FILE" ]; then
+    OLD_PID=$(cat "$PID_FILE")
+    if ps -p "$OLD_PID" > /dev/null 2>&1; then
+        echo -e "${YELLOW}⚠️  服务已在运行 (PID: $OLD_PID)${NC}"
+        echo -e "${YELLOW}如需重启,请先执行: ./stop_prod.sh${NC}"
+        exit 1
+    else
+        # PID 文件存在但进程不存在,清理旧文件
+        rm -f "$PID_FILE"
+    fi
+fi
+
+# 启动服务(后台运行)
+echo -e "${GREEN}✅ 启动 FastAPI 服务(后台模式)...${NC}"
+echo -e "${YELLOW}环境文件: $ENV_FILE${NC}"
+echo -e "${YELLOW}工作目录: $SCRIPT_DIR${NC}"
+echo ""
+
+# 使用 uvicorn 启动(生产环境建议使用 gunicorn + uvicorn workers)
+# 如果已安装 gunicorn,可以使用以下命令:
+# nohup gunicorn main:app --worker-class uvicorn.workers.UvicornWorker --workers 4 --bind 0.0.0.0:8766 > backend_nohup.log 2>&1 &
+
+# 直接使用 uvicorn 启动(适合单进程或小规模部署)
+nohup python3 -m uvicorn main:app \
+    --host 0.0.0.0 \
+    --port 8766 \
+    --workers 1 \
+    --no-access-log \
+    --log-level info \
+    > backend_nohup.log 2>&1 &
+
+BACKEND_PID=$!
+echo $BACKEND_PID > "$PID_FILE"
+
+echo -e "${GREEN}✅ 服务已启动,PID: $BACKEND_PID${NC}"
+echo -e "${YELLOW}后台日志: backend_nohup.log${NC}"
+echo -e "${YELLOW}查看状态: ./status_prod.sh${NC}"
+echo -e "${YELLOW}停止服务: ./stop_prod.sh${NC}"
+echo ""
+echo -e "${GREEN}🚀 服务启动完成!${NC}"
+

+ 104 - 0
生产环境配置/my.cnf

@@ -0,0 +1,104 @@
+[mysqld]
+# ===== 基础设置 =====
+datadir = /data/mysql/data/mysql
+socket = /data/mysql/data/mysql/mysql.sock
+port = 13306
+user = root
+
+# ===== 日志设置 =====
+log-error = /data/mysql/log/mysqld.log
+pid-file = /var/run/mysqld/mysqld.pid
+
+# 关闭慢查询日志以减少IO和内存开销
+slow_query_log = 0
+
+# ===== 连接和线程设置 =====
+# 连接池设置(4G内存优化)
+max_connections = 800
+max_connect_errors = 10000
+back_log = 500
+
+# 线程缓存(增加连接数后相应调整)
+thread_cache_size = 64
+
+# 连接超时设置
+connect_timeout = 10
+wait_timeout = 1800
+interactive_timeout = 1800
+
+# ===== 内存和缓存设置(小内存优化) =====
+# InnoDB缓冲池(4G内存下优化为70%)
+# 4G内存:800M缓冲池,4个实例
+innodb_buffer_pool_size = 800M
+innodb_buffer_pool_instances = 4
+
+# InnoDB日志设置(适当减小)
+innodb_log_file_size = 64M
+innodb_log_files_in_group = 2
+innodb_log_buffer_size = 8M
+
+# 其他InnoDB设置
+innodb_flush_log_at_trx_commit = 1
+innodb_flush_method = O_DIRECT
+innodb_file_per_table = 1
+innodb_open_files = 1024
+
+# 关闭查询缓存
+query_cache_type = 0
+query_cache_size = 0
+
+# 表缓存(增加连接数后相应调整)
+table_open_cache = 2048
+table_definition_cache = 1024
+
+# ===== 高并发优化(精简版) =====
+# InnoDB并发设置
+innodb_thread_concurrency = 0
+innodb_read_io_threads = 4
+innodb_write_io_threads = 4
+
+# 锁和事务设置
+innodb_lock_wait_timeout = 30
+transaction_isolation = READ-COMMITTED
+
+# 排序和临时表(4G内存下适当增加)
+sort_buffer_size = 256K
+read_buffer_size = 128K
+read_rnd_buffer_size = 256K
+join_buffer_size = 256K
+tmp_table_size = 32M
+max_heap_table_size = 32M
+
+# ===== 网络和包设置 =====
+max_allowed_packet = 16M
+
+# ===== 性能和安全 =====
+# 关闭性能模式以减少内存占用
+performance_schema = OFF
+
+# 安全限制(增加最大连接数)
+max_user_connections = 500
+skip_name_resolve = 1
+
+# ===== 其他优化 =====
+# 字符集
+character-set-server = utf8mb4
+collation-server = utf8mb4_unicode_ci
+
+# 默认存储引擎
+default_storage_engine = InnoDB
+
+# 禁止符号链接
+symbolic-links = 0
+
+[client]
+port = 13306
+socket = /data/mysql/data/mysql/mysql.sock
+default-character-set = utf8mb4
+
+[mysql]
+default-character-set = utf8mb4
+
+[mysqld_safe]
+log-error = /data/mysql/log/mysqld.log
+pid-file = /var/run/mysqld/mysqld.pid

+ 104 - 0
生产环境配置/my.cnf.backup

@@ -0,0 +1,104 @@
+[mysqld]
+# ===== 基础设置 =====
+datadir = /data/mysql/data/mysql
+socket = /data/mysql/data/mysql/mysql.sock
+port = 13306
+user = root
+
+# ===== 日志设置 =====
+log-error = /data/mysql/log/mysqld.log
+pid-file = /var/run/mysqld/mysqld.pid
+
+# 关闭慢查询日志以减少IO和内存开销
+slow_query_log = 0
+
+# ===== 连接和线程设置 =====
+# 连接池设置(小内存适当减少)
+max_connections = 500
+max_connect_errors = 10000
+back_log = 300
+
+# 线程缓存
+thread_cache_size = 32
+
+# 连接超时设置
+connect_timeout = 10
+wait_timeout = 1800
+interactive_timeout = 1800
+
+# ===== 内存和缓存设置(小内存优化) =====
+# InnoDB缓冲池(小内存建议物理内存的30-50%)
+# 如果是1G内存:256M,2G内存:512M
+innodb_buffer_pool_size = 256M
+innodb_buffer_pool_instances = 2
+
+# InnoDB日志设置(适当减小)
+innodb_log_file_size = 64M
+innodb_log_files_in_group = 2
+innodb_log_buffer_size = 8M
+
+# 其他InnoDB设置
+innodb_flush_log_at_trx_commit = 1
+innodb_flush_method = O_DIRECT
+innodb_file_per_table = 1
+innodb_open_files = 1024
+
+# 关闭查询缓存
+query_cache_type = 0
+query_cache_size = 0
+
+# 表缓存(适当减小)
+table_open_cache = 1024
+table_definition_cache = 512
+
+# ===== 高并发优化(精简版) =====
+# InnoDB并发设置
+innodb_thread_concurrency = 0
+innodb_read_io_threads = 4
+innodb_write_io_threads = 4
+
+# 锁和事务设置
+innodb_lock_wait_timeout = 30
+transaction_isolation = READ-COMMITTED
+
+# 排序和临时表(减小内存占用)
+sort_buffer_size = 256K
+read_buffer_size = 128K
+read_rnd_buffer_size = 256K
+join_buffer_size = 256K
+tmp_table_size = 16M
+max_heap_table_size = 16M
+
+# ===== 网络和包设置 =====
+max_allowed_packet = 16M
+
+# ===== 性能和安全 =====
+# 关闭性能模式以减少内存占用
+performance_schema = OFF
+
+# 安全限制
+max_user_connections = 300
+skip_name_resolve = 1
+
+# ===== 其他优化 =====
+# 字符集
+character-set-server = utf8mb4
+collation-server = utf8mb4_unicode_ci
+
+# 默认存储引擎
+default_storage_engine = InnoDB
+
+# 禁止符号链接
+symbolic-links = 0
+
+[client]
+port = 13306
+socket = /data/mysql/data/mysql/mysql.sock
+default-character-set = utf8mb4
+
+[mysql]
+default-character-set = utf8mb4
+
+[mysqld_safe]
+log-error = /data/mysql/log/mysqld.log
+pid-file = /var/run/mysqld/mysqld.pid

+ 280 - 0
生产环境配置/nginx.conf

@@ -0,0 +1,280 @@
+worker_processes 2; # 2核CPU,明确设置为2
+
+events {
+    worker_connections 4096;  # 每进程最大连接数(优化)
+    # use epoll; # Linux使用epoll,macOS使用kqueue(默认)
+    multi_accept on; # 批量接受新连接
+}
+
+http {
+    include       mime.types;
+    default_type  application/octet-stream;
+
+ # 错误日志
+    error_log /var/log/nginx/error.log warn;
+    # 隐藏 Nginx 版本信息
+    server_tokens off;
+
+    # 文件 I/O 性能优化
+    sendfile on;
+    tcp_nopush on;
+    tcp_nodelay on;
+
+    # 文件描述符缓存(减少系统调用)
+    open_file_cache max=10000 inactive=30s;
+    open_file_cache_valid 60s;
+    open_file_cache_min_uses 2;
+    open_file_cache_errors on;
+
+    # Keepalive 连接优化
+    keepalive_timeout 65;
+    keepalive_requests 100;
+
+    # 客户端请求限制
+    client_max_body_size 20m;
+    client_body_buffer_size 128k;
+    client_header_buffer_size 1k;
+    large_client_header_buffers 4 8k;
+
+    # 日志缓冲(提升高并发性能)
+    access_log off;  # 生产环境可关闭访问日志,或使用缓冲
+    # access_log /var/log/nginx/access.log combined buffer=32k flush=5s;
+
+    # 限流配置(4G内存优化)
+    limit_req_zone $binary_remote_addr zone=api_limit:20m rate=20r/s;
+    limit_req_zone $binary_remote_addr zone=ws_limit:20m rate=10r/s;
+    limit_conn_zone $binary_remote_addr zone=conn_limit:20m;
+
+    # 启用gzip压缩(优化压缩级别)
+    gzip on;
+    gzip_vary on;
+    gzip_min_length 1024;
+    gzip_proxied any;
+    gzip_comp_level 5;  # 降低压缩级别,平衡 CPU 和压缩比
+    gzip_types
+        text/plain
+        text/css
+        text/js
+        text/xml
+        text/javascript
+        application/javascript
+        application/xml+rss
+        application/json
+        application/wasm
+        image/svg+xml;
+
+    # HTTP 端口 80 配置,自动重定向到 HTTPS
+    server {
+        listen       80;
+        server_name  www.lyrria.com;
+        #verification.html 可以直接通过HTTP访问
+        location = /verification.html {
+         root /root/Lyrria/frontend/build;
+         try_files $uri =404;
+         add_header Cache-Control "no-cache, no-store, must-revalidate";
+         add_header Pragma "no-cache";
+         add_header Expires "0";
+        }
+
+        # 其他所有路径重定向到HTTPS
+        location / {
+          return 301 https://$host$request_uri;
+        }
+    }
+
+    server {
+        listen       443 ssl ;  # 启用 HTTP/2
+        server_name  www.lyrria.com;
+
+        ssl_certificate "/etc/nginx/cert/lyrria.com.pem";  # SSL证书位置
+        ssl_certificate_key "/etc/nginx/cert/lyrria.com.key";  # SSL证书位置
+        
+        # SSL/TLS 优化
+        ssl_session_cache shared:SSL:50m;  # 增加会话缓存大小
+        ssl_session_timeout 1h;
+        ssl_session_tickets off;  # 禁用 session tickets,使用共享缓存
+        ssl_protocols TLSv1.2 TLSv1.3;
+        ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-P
+OLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
+        ssl_prefer_server_ciphers off;  # TLS 1.3 不需要此选项
+        # ssl_dhparam /etc/nginx/cert/dhparam.pem;  # 如果存在 DH 参数文件,取消注释
+
+        # 处理favicon.ico请求
+        location = /favicon.ico {
+            root /root/Lyrria/frontend/build;
+            access_log off;
+            log_not_found off;
+            expires 1y;
+            add_header Cache-Control "public, immutable";
+        }
+
+        # 处理robots.txt请求
+        location = /robots.txt {
+            access_log off;
+            log_not_found off;
+            return 200 "User-agent: *\nDisallow:\n";
+        }
+
+        # WebSocket连接代理(使用WSS端口8766)
+        location /ws {
+            limit_req zone=ws_limit burst=20 nodelay;
+            limit_conn conn_limit 10;
+            
+            proxy_pass http://127.0.0.1:8766;
+            proxy_http_version 1.1;
+            
+            # WebSocket 必需头部
+            proxy_set_header Upgrade $http_upgrade;
+            proxy_set_header Connection "upgrade";
+            
+            # 标准代理头部
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+            proxy_set_header X-Forwarded-Host $host;
+            
+            # WebSocket 优化:禁用缓冲
+            proxy_buffering off;
+            proxy_cache off;
+            
+            # 超时设置
+            proxy_read_timeout 3600s;
+            proxy_send_timeout 3600s;
+            proxy_connect_timeout 10s;
+        }
+
+        # API接口代理(如果有REST API需求)
+        location ^~ /api/ {
+            limit_req zone=api_limit burst=40 nodelay;
+            
+            proxy_pass http://127.0.0.1:8766$request_uri;
+            
+            # 代理头部
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+            proxy_set_header X-Forwarded-Host $host;
+            
+            # 代理缓冲优化
+            proxy_buffering on;
+            proxy_buffer_size 4k;
+            proxy_buffers 8 4k;
+            proxy_busy_buffers_size 8k;
+            proxy_temp_file_write_size 8k;
+            
+            # 超时设置
+            proxy_read_timeout 60s;
+            proxy_send_timeout 60s;
+            proxy_connect_timeout 10s;
+        }
+        # 客户端指标上报接口代理
+        location = /metrics/client {
+            limit_req zone=api_limit burst=20 nodelay;
+            
+            proxy_pass http://127.0.0.1:8766/metrics/client;
+            
+            # 代理头部
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+            proxy_set_header X-Forwarded-Host $host;
+            
+            # 代理缓冲
+            proxy_buffering on;
+            proxy_buffer_size 4k;
+            proxy_buffers 4 4k;
+            
+            # 超时设置
+            proxy_read_timeout 60s;
+            proxy_send_timeout 60s;
+            proxy_connect_timeout 10s;
+        }
+
+        # HTML 文件处理(独立 location,修复嵌套问题)
+        location ~* \.html$ {
+            root /root/Lyrria/frontend/build;
+            try_files $uri =404;
+            
+            # 处理 OPTIONS 预检请求
+            if ($request_method = 'OPTIONS') {
+                add_header Access-Control-Allow-Origin '*' always;
+                add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+                add_header Access-Control-Max-Age 1728000 always;
+                add_header Content-Type 'text/plain; charset=utf-8' always;
+                add_header Content-Length 0 always;
+                return 204;
+            }
+            
+            # HTML 文件不缓存
+            add_header Cache-Control "no-cache, no-store, must-revalidate" always;
+            add_header Pragma "no-cache" always;
+            add_header Expires "0" always;
+            
+            # 安全头设置
+            add_header X-Frame-Options "SAMEORIGIN" always;
+            add_header X-Content-Type-Options "nosniff" always;
+            add_header X-XSS-Protection "1; mode=block" always;
+            add_header Referrer-Policy "strict-origin-when-cross-origin" always;
+            
+            # CORS 响应头
+            add_header Access-Control-Allow-Origin '*' always;
+            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+            add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+        }
+
+        # 静态资源缓存配置(支持跨域)
+        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|webp|avif)$ {
+            # 处理 OPTIONS 预检请求
+            if ($request_method = 'OPTIONS') {
+                add_header Access-Control-Allow-Origin '*' always;
+                add_header Access-Control-Allow-Methods 'GET, OPTIONS' always;
+                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
+                add_header Access-Control-Max-Age 1728000 always;
+                add_header Content-Type 'text/plain; charset=utf-8' always;
+                add_header Content-Length 0 always;
+                return 204;
+            }
+
+            root /root/Lyrria/frontend/build;
+            expires 1y;
+            add_header Cache-Control "public, max-age=31536000, immutable" always;
+            add_header X-Content-Type-Options nosniff always;
+            
+            # CORS 响应头
+            add_header Access-Control-Allow-Origin '*' always;
+            add_header Access-Control-Allow-Methods 'GET, OPTIONS' always;
+        }
+
+        # 前端静态文件服务(SPA 路由)
+        location / {
+            # 处理 OPTIONS 预检请求
+            if ($request_method = 'OPTIONS') {
+                add_header Access-Control-Allow-Origin '*' always;
+                add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+                add_header Access-Control-Max-Age 1728000 always;
+                add_header Content-Type 'text/plain; charset=utf-8' always;
+                add_header Content-Length 0 always;
+                return 204;
+            }
+            
+            root /root/Lyrria/frontend/build;
+            try_files $uri $uri/ /index.html;
+            
+            # 安全头设置
+            add_header X-Frame-Options "SAMEORIGIN" always;
+            add_header X-Content-Type-Options "nosniff" always;
+            add_header X-XSS-Protection "1; mode=block" always;
+            add_header Referrer-Policy "strict-origin-when-cross-origin" always;
+            
+            # CORS 响应头
+            add_header Access-Control-Allow-Origin '*' always;
+            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+            add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+        }
+    }
+} 

+ 280 - 0
生产环境配置/nginx.conf.backup

@@ -0,0 +1,280 @@
+worker_processes auto; # 自动匹配 CPU 核数
+
+events {
+    worker_connections 8192;  # 每进程最大连接数
+    use epoll; # 使用高效事件模型
+    multi_accept on; # 批量接受新连接
+}
+
+http {
+    include       mime.types;
+    default_type  application/octet-stream;
+
+ # 错误日志
+    error_log /var/log/nginx/error.log warn;
+    # 隐藏 Nginx 版本信息
+    server_tokens off;
+
+    # 文件 I/O 性能优化
+    sendfile on;
+    tcp_nopush on;
+    tcp_nodelay on;
+
+    # 文件描述符缓存(减少系统调用)
+    open_file_cache max=10000 inactive=30s;
+    open_file_cache_valid 60s;
+    open_file_cache_min_uses 2;
+    open_file_cache_errors on;
+
+    # Keepalive 连接优化
+    keepalive_timeout 65;
+    keepalive_requests 100;
+
+    # 客户端请求限制
+    client_max_body_size 10m;
+    client_body_buffer_size 128k;
+    client_header_buffer_size 1k;
+    large_client_header_buffers 4 8k;
+
+    # 日志缓冲(提升高并发性能)
+    access_log off;  # 生产环境可关闭访问日志,或使用缓冲
+    # access_log /var/log/nginx/access.log combined buffer=32k flush=5s;
+
+    # 限流配置
+    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
+    limit_req_zone $binary_remote_addr zone=ws_limit:10m rate=5r/s;
+    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
+
+    # 启用gzip压缩(优化压缩级别)
+    gzip on;
+    gzip_vary on;
+    gzip_min_length 1024;
+    gzip_proxied any;
+    gzip_comp_level 5;  # 降低压缩级别,平衡 CPU 和压缩比
+    gzip_types
+        text/plain
+        text/css
+        text/js
+        text/xml
+        text/javascript
+        application/javascript
+        application/xml+rss
+        application/json
+        application/wasm
+        image/svg+xml;
+
+    # HTTP 端口 80 配置,自动重定向到 HTTPS
+    server {
+        listen       80;
+        server_name  www.lyrria.com;
+        #verification.html 可以直接通过HTTP访问
+        location = /verification.html {
+         root /root/Lyrria/frontend/build;
+         try_files $uri =404;
+         add_header Cache-Control "no-cache, no-store, must-revalidate";
+         add_header Pragma "no-cache";
+         add_header Expires "0";
+        }
+
+        # 其他所有路径重定向到HTTPS
+        location / {
+          return 301 https://$host$request_uri;
+        }
+    }
+
+    server {
+        listen       443 ssl ;  # 启用 HTTP/2
+        server_name  www.lyrria.com;
+
+        ssl_certificate "/etc/nginx/cert/lyrria.com.pem";  # SSL证书位置
+        ssl_certificate_key "/etc/nginx/cert/lyrria.com.key";  # SSL证书位置
+        
+        # SSL/TLS 优化
+        ssl_session_cache shared:SSL:50m;  # 增加会话缓存大小
+        ssl_session_timeout 1h;
+        ssl_session_tickets off;  # 禁用 session tickets,使用共享缓存
+        ssl_protocols TLSv1.2 TLSv1.3;
+        ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-P
+OLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
+        ssl_prefer_server_ciphers off;  # TLS 1.3 不需要此选项
+        # ssl_dhparam /etc/nginx/cert/dhparam.pem;  # 如果存在 DH 参数文件,取消注释
+
+        # 处理favicon.ico请求
+        location = /favicon.ico {
+            root /root/Lyrria/frontend/build;
+            access_log off;
+            log_not_found off;
+            expires 1y;
+            add_header Cache-Control "public, immutable";
+        }
+
+        # 处理robots.txt请求
+        location = /robots.txt {
+            access_log off;
+            log_not_found off;
+            return 200 "User-agent: *\nDisallow:\n";
+        }
+
+        # WebSocket连接代理(使用WSS端口8766)
+        location /ws {
+            limit_req zone=ws_limit burst=10 nodelay;
+            limit_conn conn_limit 10;
+            
+            proxy_pass http://127.0.0.1:8766;
+            proxy_http_version 1.1;
+            
+            # WebSocket 必需头部
+            proxy_set_header Upgrade $http_upgrade;
+            proxy_set_header Connection "upgrade";
+            
+            # 标准代理头部
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+            proxy_set_header X-Forwarded-Host $host;
+            
+            # WebSocket 优化:禁用缓冲
+            proxy_buffering off;
+            proxy_cache off;
+            
+            # 超时设置
+            proxy_read_timeout 3600s;
+            proxy_send_timeout 3600s;
+            proxy_connect_timeout 10s;
+        }
+
+        # API接口代理(如果有REST API需求)
+        location ^~ /api/ {
+            limit_req zone=api_limit burst=20 nodelay;
+            
+            proxy_pass http://127.0.0.1:8766$request_uri;
+            
+            # 代理头部
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+            proxy_set_header X-Forwarded-Host $host;
+            
+            # 代理缓冲优化
+            proxy_buffering on;
+            proxy_buffer_size 4k;
+            proxy_buffers 8 4k;
+            proxy_busy_buffers_size 8k;
+            proxy_temp_file_write_size 8k;
+            
+            # 超时设置
+            proxy_read_timeout 60s;
+            proxy_send_timeout 60s;
+            proxy_connect_timeout 10s;
+        }
+        # 客户端指标上报接口代理
+        location = /metrics/client {
+            limit_req zone=api_limit burst=10 nodelay;
+            
+            proxy_pass http://127.0.0.1:8766/metrics/client;
+            
+            # 代理头部
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+            proxy_set_header X-Forwarded-Host $host;
+            
+            # 代理缓冲
+            proxy_buffering on;
+            proxy_buffer_size 4k;
+            proxy_buffers 4 4k;
+            
+            # 超时设置
+            proxy_read_timeout 60s;
+            proxy_send_timeout 60s;
+            proxy_connect_timeout 10s;
+        }
+
+        # HTML 文件处理(独立 location,修复嵌套问题)
+        location ~* \.html$ {
+            root /root/Lyrria/frontend/build;
+            try_files $uri =404;
+            
+            # 处理 OPTIONS 预检请求
+            if ($request_method = 'OPTIONS') {
+                add_header Access-Control-Allow-Origin '*' always;
+                add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+                add_header Access-Control-Max-Age 1728000 always;
+                add_header Content-Type 'text/plain; charset=utf-8' always;
+                add_header Content-Length 0 always;
+                return 204;
+            }
+            
+            # HTML 文件不缓存
+            add_header Cache-Control "no-cache, no-store, must-revalidate" always;
+            add_header Pragma "no-cache" always;
+            add_header Expires "0" always;
+            
+            # 安全头设置
+            add_header X-Frame-Options "SAMEORIGIN" always;
+            add_header X-Content-Type-Options "nosniff" always;
+            add_header X-XSS-Protection "1; mode=block" always;
+            add_header Referrer-Policy "strict-origin-when-cross-origin" always;
+            
+            # CORS 响应头
+            add_header Access-Control-Allow-Origin '*' always;
+            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+            add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+        }
+
+        # 静态资源缓存配置(支持跨域)
+        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|webp|avif)$ {
+            # 处理 OPTIONS 预检请求
+            if ($request_method = 'OPTIONS') {
+                add_header Access-Control-Allow-Origin '*' always;
+                add_header Access-Control-Allow-Methods 'GET, OPTIONS' always;
+                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
+                add_header Access-Control-Max-Age 1728000 always;
+                add_header Content-Type 'text/plain; charset=utf-8' always;
+                add_header Content-Length 0 always;
+                return 204;
+            }
+
+            root /root/Lyrria/frontend/build;
+            expires 1y;
+            add_header Cache-Control "public, max-age=31536000, immutable" always;
+            add_header X-Content-Type-Options nosniff always;
+            
+            # CORS 响应头
+            add_header Access-Control-Allow-Origin '*' always;
+            add_header Access-Control-Allow-Methods 'GET, OPTIONS' always;
+        }
+
+        # 前端静态文件服务(SPA 路由)
+        location / {
+            # 处理 OPTIONS 预检请求
+            if ($request_method = 'OPTIONS') {
+                add_header Access-Control-Allow-Origin '*' always;
+                add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+                add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+                add_header Access-Control-Max-Age 1728000 always;
+                add_header Content-Type 'text/plain; charset=utf-8' always;
+                add_header Content-Length 0 always;
+                return 204;
+            }
+            
+            root /root/Lyrria/frontend/build;
+            try_files $uri $uri/ /index.html;
+            
+            # 安全头设置
+            add_header X-Frame-Options "SAMEORIGIN" always;
+            add_header X-Content-Type-Options "nosniff" always;
+            add_header X-XSS-Protection "1; mode=block" always;
+            add_header Referrer-Policy "strict-origin-when-cross-origin" always;
+            
+            # CORS 响应头
+            add_header Access-Control-Allow-Origin '*' always;
+            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
+            add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
+        }
+    }
+} 

+ 190 - 0
生产环境配置/redis.conf

@@ -0,0 +1,190 @@
+# Redis configuration file for CentOS 7.9 - Optimized for high concurrency
+
+################################## NETWORK #####################################
+
+# 绑定地址,建议限制访问范围
+#bind 127.0.0.1
+# 如果确实需要外部访问且已配置防火墙:
+bind 0.0.0.0
+
+# 保护模式开启,确保安全
+protected-mode yes
+
+# 修改端口为16379
+port 16379
+
+# 提高TCP backlog以适应高并发(需配合系统参数)
+tcp-backlog 131072
+
+# 保持长连接,减少连接建立开销
+timeout 300
+
+# TCP keepalive设置(增加到5分钟)
+tcp-keepalive 300
+
+################################# GENERAL #####################################
+
+# 以守护进程运行
+daemonize yes
+
+# 不使用systemd管理(因为用root直接启动)
+supervised no
+
+# PID文件路径
+pidfile /var/run/redis_16379.pid
+
+# 日志级别
+loglevel notice
+
+# 日志文件路径
+logfile /var/log/redis/redis_16379.log
+
+# 数据库数量,减少不必要的内存占用
+databases 8
+
+################################ SNAPSHOTTING  ################################
+
+# 根据内存限制调整持久化策略,减少频繁写入
+save 900 1
+save 300 10
+save 60 10000
+
+# 在bgsave出错时继续接受写入
+stop-writes-on-bgsave-error no
+
+# 启用RDB压缩
+rdbcompression yes
+
+# RDB校验
+rdbchecksum yes
+
+# RDB文件名
+dbfilename dump_16379.rdb
+
+# 工作目录
+dir /var/lib/redis/16379
+
+################################## SECURITY ###################################
+
+# 设置密码
+requirepass Lyrria@redis@123456
+
+# 重命名危险命令,提高安全性
+rename-command FLUSHDB ""
+rename-command FLUSHALL ""
+rename-command CONFIG ""
+
+################################### CLIENTS ####################################
+
+# 最大客户端连接数,根据服务器资源调整
+maxclients 10000
+
+############################## MEMORY MANAGEMENT ################################
+
+# 最大内存限制,4G服务器优化为2GB
+maxmemory 2gb
+
+# 内存淘汰策略
+maxmemory-policy allkeys-lru
+
+# LRU采样精度
+maxmemory-samples 5
+
+# 副本忽略maxmemory设置
+replica-ignore-maxmemory yes
+
+############################# LAZY FREEING ####################################
+
+# 启用惰性删除,减少阻塞
+lazyfree-lazy-eviction yes
+lazyfree-lazy-expire yes
+lazyfree-lazy-server-del yes
+replica-lazy-flush yes
+
+################################ THREADED I/O #################################
+
+# 启用I/O线程,2核CPU优化配置
+io-threads 3
+io-threads-do-reads yes
+
+############################## APPEND ONLY MODE ###############################
+
+# 根据性能需求选择是否启用AOF
+appendonly no
+
+# 如果启用AOF,使用每秒同步
+appendfsync everysec
+
+# 重写时不同步
+no-appendfsync-on-rewrite yes
+
+# AOF重写配置
+auto-aof-rewrite-percentage 100
+auto-aof-rewrite-min-size 64mb
+
+################################## SLOW LOG ###################################
+
+# 慢查询日志配置
+slowlog-log-slower-than 10000
+slowlog-max-len 1024
+
+################################ LATENCY MONITOR ##############################
+
+# 延迟监控
+latency-monitor-threshold 100
+
+############################### ADVANCED CONFIG ###############################
+
+# 哈希配置优化
+hash-max-ziplist-entries 512
+hash-max-ziplist-value 64
+
+# 列表配置优化
+list-max-ziplist-size -2
+list-compress-depth 0
+
+# 集合配置优化
+set-max-intset-entries 512
+
+# 有序集合配置优化
+zset-max-ziplist-entries 128
+zset-max-ziplist-value 64
+
+# HyperLogLog配置
+hll-sparse-max-bytes 3000
+
+# 流配置
+stream-node-max-bytes 4096
+stream-node-max-entries 100
+
+# 主动重哈希
+activerehashing yes
+
+# 客户端输出缓冲区限制
+client-output-buffer-limit normal 0 0 0
+client-output-buffer-limit replica 256mb 64mb 60
+client-output-buffer-limit pubsub 32mb 8mb 60
+
+# 协议最大批量长度
+proto-max-bulk-len 512mb
+
+# Hz值调整
+hz 10
+dynamic-hz yes
+
+# 增量fsync
+aof-rewrite-incremental-fsync yes
+rdb-save-incremental-fsync yes
+
+########################### ACTIVE DEFRAGMENTATION #######################
+
+# 内存碎片整理配置
+activedefrag no
+active-defrag-ignore-bytes 100mb
+active-defrag-threshold-lower 10
+active-defrag-threshold-upper 100
+active-defrag-cycle-min 1
+active-defrag-cycle-max 25
+
+# Jemalloc后台线程
+jemalloc-bg-thread yes

+ 190 - 0
生产环境配置/redis.conf.backup

@@ -0,0 +1,190 @@
+# Redis configuration file for CentOS 7.9 - Optimized for high concurrency
+
+################################## NETWORK #####################################
+
+# 绑定地址,建议限制访问范围
+#bind 127.0.0.1
+# 如果确实需要外部访问且已配置防火墙:
+bind 0.0.0.0
+
+# 保护模式开启,确保安全
+protected-mode yes
+
+# 修改端口为16379
+port 16379
+
+# 提高TCP backlog以适应高并发(需配合系统参数)
+tcp-backlog 65535
+
+# 保持长连接,减少连接建立开销
+timeout 300
+
+# TCP keepalive设置
+tcp-keepalive 60
+
+################################# GENERAL #####################################
+
+# 以守护进程运行
+daemonize yes
+
+# 不使用systemd管理(因为用root直接启动)
+supervised no
+
+# PID文件路径
+pidfile /var/run/redis_16379.pid
+
+# 日志级别
+loglevel notice
+
+# 日志文件路径
+logfile /var/log/redis/redis_16379.log
+
+# 数据库数量,减少不必要的内存占用
+databases 8
+
+################################ SNAPSHOTTING  ################################
+
+# 根据内存限制调整持久化策略,减少频繁写入
+save 900 1
+save 300 10
+save 60 10000
+
+# 在bgsave出错时继续接受写入
+stop-writes-on-bgsave-error no
+
+# 启用RDB压缩
+rdbcompression yes
+
+# RDB校验
+rdbchecksum yes
+
+# RDB文件名
+dbfilename dump_16379.rdb
+
+# 工作目录
+dir /var/lib/redis/16379
+
+################################## SECURITY ###################################
+
+# 设置密码
+requirepass Lyrria@redis@123456
+
+# 重命名危险命令,提高安全性
+rename-command FLUSHDB ""
+rename-command FLUSHALL ""
+rename-command CONFIG ""
+
+################################### CLIENTS ####################################
+
+# 最大客户端连接数,根据服务器资源调整
+maxclients 10000
+
+############################## MEMORY MANAGEMENT ################################
+
+# 最大内存限制,根据服务器实际内存设置
+maxmemory 1gb
+
+# 内存淘汰策略
+maxmemory-policy allkeys-lru
+
+# LRU采样精度
+maxmemory-samples 5
+
+# 副本忽略maxmemory设置
+replica-ignore-maxmemory yes
+
+############################# LAZY FREEING ####################################
+
+# 启用惰性删除,减少阻塞
+lazyfree-lazy-eviction yes
+lazyfree-lazy-expire yes
+lazyfree-lazy-server-del yes
+replica-lazy-flush yes
+
+################################ THREADED I/O #################################
+
+# 启用I/O线程,根据CPU核心数调整
+io-threads 2
+io-threads-do-reads no
+
+############################## APPEND ONLY MODE ###############################
+
+# 根据性能需求选择是否启用AOF
+appendonly no
+
+# 如果启用AOF,使用每秒同步
+appendfsync everysec
+
+# 重写时不同步
+no-appendfsync-on-rewrite yes
+
+# AOF重写配置
+auto-aof-rewrite-percentage 100
+auto-aof-rewrite-min-size 64mb
+
+################################## SLOW LOG ###################################
+
+# 慢查询日志配置
+slowlog-log-slower-than 10000
+slowlog-max-len 1024
+
+################################ LATENCY MONITOR ##############################
+
+# 延迟监控
+latency-monitor-threshold 100
+
+############################### ADVANCED CONFIG ###############################
+
+# 哈希配置优化
+hash-max-ziplist-entries 512
+hash-max-ziplist-value 64
+
+# 列表配置优化
+list-max-ziplist-size -2
+list-compress-depth 0
+
+# 集合配置优化
+set-max-intset-entries 512
+
+# 有序集合配置优化
+zset-max-ziplist-entries 128
+zset-max-ziplist-value 64
+
+# HyperLogLog配置
+hll-sparse-max-bytes 3000
+
+# 流配置
+stream-node-max-bytes 4096
+stream-node-max-entries 100
+
+# 主动重哈希
+activerehashing yes
+
+# 客户端输出缓冲区限制
+client-output-buffer-limit normal 0 0 0
+client-output-buffer-limit replica 256mb 64mb 60
+client-output-buffer-limit pubsub 32mb 8mb 60
+
+# 协议最大批量长度
+proto-max-bulk-len 512mb
+
+# Hz值调整
+hz 10
+dynamic-hz yes
+
+# 增量fsync
+aof-rewrite-incremental-fsync yes
+rdb-save-incremental-fsync yes
+
+########################### ACTIVE DEFRAGMENTATION #######################
+
+# 内存碎片整理配置
+activedefrag no
+active-defrag-ignore-bytes 100mb
+active-defrag-threshold-lower 10
+active-defrag-threshold-upper 100
+active-defrag-cycle-min 1
+active-defrag-cycle-max 25
+
+# Jemalloc后台线程
+jemalloc-bg-thread yes

+ 311 - 0
项目文档/2核4G服务器综合优化方案.md

@@ -0,0 +1,311 @@
+# 2核4G服务器综合优化方案
+
+## 环境现状
+
+- **服务器配置**: 阿里云ECS 2核4G (从2核2G升级)
+- **服务架构**: MySQL + Redis + Nginx + FastAPI后端
+- **目标**: 充分利用新增内存,提高并发处理能力
+
+---
+
+## 优化方案总览
+
+### 内存分配策略 (4G总内存)
+- **MySQL**: 1GB (缓冲池800M + 其他200M)
+- **Redis**: 2GB (缓存数据)
+- **系统/应用**: 1GB (系统缓存 + 应用运行)
+- **预期效果**: 并发能力提升约150-200%
+
+---
+
+## 1. MySQL优化配置
+
+### 核心优化项
+
+**缓冲池内存调整** (影响最大)
+```ini
+# 原来: 256M → 优化: 800M (缓冲池)
+innodb_buffer_pool_size = 800M
+innodb_buffer_pool_instances = 4  # 2核CPU,增加实例数
+```
+
+**连接和并发优化**
+```ini
+# 连接数适当增加 (原来500)
+max_connections = 800
+max_user_connections = 500
+
+# 线程缓存优化
+thread_cache_size = 64
+```
+
+**其他关键调整**
+```ini
+# 临时表和排序优化
+tmp_table_size = 32M
+max_heap_table_size = 32M
+
+# 缓存优化
+table_open_cache = 2048
+table_definition_cache = 1024
+```
+
+### 预期效果
+- **查询性能**: 提升200-300%
+- **并发连接**: 从500提升到800
+- **内存利用率**: 从256M提升到800M
+
+---
+
+## 2. Redis优化配置
+
+### 核心优化项
+
+**内存容量调整**
+```ini
+# 原来: 1GB → 优化: 2GB
+maxmemory 2gb
+```
+
+**并发性能优化**
+```ini
+# I/O线程数调整 (2核CPU)
+io-threads 3  # 原来2,增加到3
+io-threads-do-reads yes  # 启用I/O线程读取
+```
+
+**连接优化**
+```ini
+# TCP优化
+tcp-backlog 131072  # 原来65535,提升到131072
+tcp-keepalive 300   # 原来60,增加到300秒
+```
+
+### 预期效果
+- **内存容量**: 从1GB提升到2GB
+- **I/O性能**: 提升30-50%
+- **连接处理**: 更稳定的长连接
+
+---
+
+## 3. Nginx优化配置
+
+### 核心优化项
+
+**限流策略调整** (适应新增资源)
+```nginx
+# 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;
+```
+
+**性能优化**
+```nginx
+# 工作进程数 (2核CPU)
+worker_processes 2;  # 明确设置为2
+
+# 连接数优化
+worker_connections 4096;  # 原来8192,调整为4096更合适
+
+# 缓冲区优化
+client_max_body_size 20m;  # 原来10m
+```
+
+### 预期效果
+- **API请求**: 从10r/s提升到20r/s
+- **WebSocket连接**: 从5r/s提升到10r/s
+- **并发连接**: 更稳定的处理能力
+
+---
+
+## 4. 后端服务优化
+
+### 启动方式升级
+
+**从单进程uvicorn升级为gunicorn多进程**
+```bash
+# 安装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
+```
+
+### 预期效果
+- **并发处理**: 4个worker进程
+- **稳定性**: 自动重启机制
+- **内存管理**: 更好的内存回收
+
+---
+
+## 5. 系统层面优化
+
+### 内核参数调整 (可选)
+
+创建 `/etc/sysctl.d/99-lyrria.conf`:
+```bash
+# 网络优化
+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`:
+```bash
+* soft nofile 65536
+* hard nofile 65536
+* soft nproc  65536
+* hard nproc  65536
+```
+
+---
+
+## 6. 部署顺序
+
+### 优化实施步骤
+
+1. **备份当前配置**
+   ```bash
+   cp 生产环境配置/my.cnf 生产环境配置/my.cnf.backup
+   cp 生产环境配置/redis.conf 生产环境配置/redis.conf.backup
+   cp 生产环境配置/nginx.conf 生产环境配置/nginx.conf.backup
+   ```
+
+2. **按顺序重启服务**
+   ```bash
+   # 1. 停止应用服务
+   cd backend && ./stop_prod.sh
+
+   # 2. 重启MySQL
+   sudo systemctl restart mysqld
+
+   # 3. 重启Redis
+   sudo systemctl restart redis
+
+   # 4. 重启Nginx
+   sudo systemctl restart nginx
+
+   # 5. 启动应用服务
+   cd backend && ./start_prod.sh
+   ```
+
+3. **验证配置**
+   ```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监控**
+```bash
+# 内存使用
+redis-cli info memory
+
+# 连接数
+redis-cli info clients
+
+# 性能统计
+redis-cli info stats
+```
+
+**系统监控**
+```bash
+# CPU使用率
+top -b -n1 | head -10
+
+# 内存使用
+free -h
+
+# 磁盘I/O
+iostat -x 1 5
+```
+
+---
+
+## 8. 预期性能提升
+
+| 组件 | 优化前 | 优化后 | 提升幅度 |
+|------|--------|--------|----------|
+| 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%** |
+
+---
+
+## 9. 注意事项
+
+### 风险控制
+- **渐进式调整**: 先调整50%配置,观察效果后再调整
+- **监控告警**: 设置关键指标告警
+- **回滚准备**: 保留原配置文件备份
+
+### 观察要点
+- **内存使用**: 确保不超过90%
+- **CPU使用率**: 2核CPU,避免长期超过80%
+- **响应时间**: API响应时间不应明显增加
+- **错误率**: 各服务错误率不应上升
+
+---
+
+## 10. 后续优化建议
+
+### 中期优化 (1-2周后)
+- 启用MySQL性能模式进行深度分析
+- 考虑启用Redis持久化
+- 优化应用代码层面的性能瓶颈
+
+### 长期优化 (1个月后)
+- 考虑读写分离架构
+- 实施更细粒度的缓存策略
+- 监控用户行为模式,优化资源分配
+
+---
+
+*最后更新: 2025年12月29日*