数据库连接中断可能由以下原因导致: 1. 网络问题(连接超时、防火墙限制) 2. 数据库服务崩溃或重启 3. 资源不足(内存、CPU、连接数) 4. 配置不当(超时设置过短) 5. 数据库维护或备份操作
# 测试数据库端口是否可达
telnet <数据库IP> <端口>
或
nc -zv <数据库IP> <端口>
# 检查路由和丢包情况
traceroute <数据库IP>
ping <数据库IP> -c 10
# MySQL/MariaDB
systemctl status mysqld
或
systemctl status mariadb
# PostgreSQL
systemctl status postgresql
# MongoDB
systemctl status mongod
# MySQL/MariaDB
tail -n 50 /var/log/mysql/error.log
或
journalctl -u mysqld --no-pager -n 50
# PostgreSQL
tail -n 50 /var/log/postgresql/postgresql-*.log
# MongoDB
tail -n 50 /var/log/mongodb/mongod.log
# 查看系统资源
top
htop
free -m
# 查看数据库连接数
# MySQL
mysql -e "SHOW STATUS LIKE 'Threads_connected';"
# PostgreSQL
psql -c "SELECT count(*) FROM pg_stat_activity;"
对于MySQL/MariaDB,编辑/etc/my.cnf
或/etc/mysql/my.cnf
:
[mysqld]
wait_timeout = 28800
interactive_timeout = 28800
max_connections = 200
对于PostgreSQL,编辑postgresql.conf
:
tcp_keepalives_idle = 60
tcp_keepalives_interval = 10
tcp_keepalives_count = 5
max_connections = 200
在应用端配置连接池参数: - 最大连接数 - 最小空闲连接数 - 连接超时时间 - 连接验证查询
# 允许数据库端口
iptables -A INPUT -p tcp --dport <数据库端口> -j ACCEPT
# 或使用firewalld
firewall-cmd --permanent --add-port=<数据库端口>/tcp
firewall-cmd --reload
在应用代码中添加重连逻辑,例如:
# Python示例
import time
import mysql.connector
from mysql.connector import Error
def create_connection():
while True:
try:
conn = mysql.connector.connect(
host='localhost',
database='mydb',
user='user',
password='password'
)
return conn
except Error as e:
print(f"连接失败: {e}")
time.sleep(5) # 等待5秒后重试
设置监控系统检测数据库连接状态: - Prometheus + Grafana - Zabbix - Nagios
如果问题持续存在,建议收集以下信息提交给专业DBA进一步分析: - 完整的数据库错误日志 - 系统资源使用历史数据 - 网络质量报告 - 应用程序连接池配置