Files
Django/deploy/fix-db-latency.sh
2026-07-09 04:39:32 +08:00

78 lines
2.7 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# 诊断并修复 API 延迟:对比本机 Docker MySQL vs 远程 gvsds.com
# 在服务器上执行bash deploy/fix-db-latency.sh
set -e
DJANGO_DIR="/opt/1panel/apps/openresty/nginx/www/sites/43.142.166.152.443/django"
cd "$DJANGO_DIR"
echo "========== 1. Gunicorn 状态 =========="
systemctl is-active gunicorn-dianjing.service || true
pgrep -af 'gunicorn.*a_long_dianjing' || echo "无 gunicorn 进程!"
echo ""
echo "========== 2. 当前数据库配置 =========="
python3 - <<'PY'
import app_secrets
print(f"HOST={app_secrets.DATABASE_HOST} PORT={app_secrets.DATABASE_PORT} DB={app_secrets.DATABASE_NAME}")
PY
echo ""
echo "========== 3. 连接延迟对比(新建连接 + 简单查询)=========="
python3 - <<'PY'
import time
import pymysql
import app_secrets
def test_host(host, port, user, password, db):
t0 = time.time()
try:
conn = pymysql.connect(
host=host, port=int(port), user=user, password=password,
database=db, connect_timeout=5, charset='utf8mb4',
)
connect_ms = (time.time() - t0) * 1000
t1 = time.time()
with conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
query_ms = (time.time() - t1) * 1000
conn.close()
return connect_ms, query_ms, None
except Exception as e:
return None, None, str(e)
user = app_secrets.DATABASE_USER
pwd = app_secrets.DATABASE_PASSWORD
db = app_secrets.DATABASE_NAME
cur_host = app_secrets.DATABASE_HOST
cur_port = app_secrets.DATABASE_PORT
for label, host, port in [
("当前生产", cur_host, cur_port),
("本机 Docker", "172.17.0.15", "3306"),
]:
c, q, err = test_host(host, port, user, pwd, db)
if err:
print(f" [{label}] {host}:{port} -> 失败: {err}")
else:
print(f" [{label}] {host}:{port} -> 握手 {c:.0f}ms, 查询 {q:.0f}ms")
print("\n若本机 Docker 成功且 <20ms应改 app_secrets.py 的 DATABASE_HOST=172.17.0.15 PORT=3306")
PY
echo ""
echo "========== 4. 本地 API 响应ddhq 需 token测空接口=========="
curl -s -o /dev/null -w "127.0.0.1:8001 响应: %{time_total}s\n" http://127.0.0.1:8001/hqhd/ 2>/dev/null || echo "8001 无响应"
echo ""
echo "========== 5. Nginx 最近 hqhd 延迟rt==========="
grep 'hqhd' /opt/1panel/apps/openresty/nginx/log/access.log 2>/dev/null | tail -5 || echo "无日志"
echo ""
echo "========== 修复步骤(本机库可用时)=========="
echo "1. 备份: cp app_secrets.py app_secrets.py.bak.\$(date +%Y%m%d)"
echo "2. 改 DATABASE_HOST='172.17.0.15' DATABASE_PORT='3306'"
echo "3. systemctl restart gunicorn-dianjing.service"
echo "4. 再 grep hqhd access.log 看 rt= 是否回到 0.05~0.08"