在CentOS環境中優化數據庫性能是一個涉及多個方面的過程,以下是一些關鍵的優化策略:
/etc/sysctl.conf
文件,增加以下配置:vm.swappiness = 10
fs.file-max = 100000
net.core.somaxconn = 1024
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
應用修改:sudo sysctl -p
/etc/security/limits.conf
文件,設置 MySQL 的文件描述符限制:mysql soft nofile 65535
mysql hard nofile 65535
確保 MySQL 啟動腳本或 systemd 中也包含:LimitNOFILE 65535
/etc/my.cnf
文件,根據服務器內存和業務量調整以下參數:[mysqld]
max_connections = 200
query_cache_type = 0
query_cache_size = 0
innodb_buffer_pool_size = 2G # 通常為物理內存的 50%-80%
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_file_per_table = 1
tmp_table_size = 64M
max_heap_table_size = 64M
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
mysqltuner
工具分析慢查詢日志。SELECT id, name FROM users;
SELECT * FROM table WHERE id > 100000 LIMIT 10;
mysql -u root -p --protocol=socket
/etc/my.cnf
文件,設置 bind-address = 127.0.0.1
,如需遠程開放,則配置防火墻和用戶權限限制。SHOW ENGINE INNODB STATUS;
mysqldump
定期備份數據庫。SHOW STATUS LIKE 'Threads_connected';
和 SHOW GLOBAL STATUS LIKE 'Uptime';
通過上述方法,可以顯著提升 CentOS 環境下數據庫的性能和穩定性。需要注意的是,不同的應用場景可能需要不同的優化策略,因此在進行優化時,建議根據具體情況進行調整。