在 CentOS 上优化 MySQL 性能,通常可以从 系统层面、MySQL 配置、Schema 与 SQL、监控与维护 四个方面入手。下面给你一份实用、可落地的优化指南(以 CentOS 7/8 + MySQL 5.7/8.0 为例)。
systemctl disable firewalld --now # 如不在公网可关
systemctl disable postfix
# 文件句柄
fs.file-max = 1000000
# TCP 连接
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
# Swap 使用策略
vm.swappiness = 10
执行:
sysctl -p
/etc/security/limits.conf
mysql soft nofile 65535
mysql hard nofile 65535
defaults,noatime,nodiratime
配置文件位置:
/etc/my.cnf
或
/etc/my.cnf.d/server.cnf
[mysqld]
# 缓冲池(最重要)
innodb_buffer_pool_size = 10G
innodb_buffer_pool_instances = 8
# 日志
innodb_log_file_size = 1G
innodb_log_files_in_group = 2
innodb_flush_log_at_trx_commit = 2
sync_binlog = 0
# 连接
max_connections = 500
max_allowed_packet = 64M
innodb_io_capacity = 2000
innodb_io_capacity_max = 4000
innodb_thread_concurrency = 0
MySQL 5.7:
query_cache_type = 0
query_cache_size = 0
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
log_queries_not_using_indexes = 1
重启 MySQL:
systemctl restart mysqld
TEXT/BLOB 滥用NOT NULLEXPLAIN SELECT * FROM user WHERE name='tom';
原则:
WHERE DATE(created)=)SELECT *LIKE '%xx'-- 不推荐
LIMIT 1000000,10
-- 推荐
WHERE id > 1000000 LIMIT 10
OPTIMIZE TABLE table_name; # 小表
ANALYZE TABLE table_name;
SHOW PROCESSLIST;SHOW GLOBAL STATUS;| 现象 | 可能原因 |
|---|---|
| CPU 高 | 慢 SQL / 缺索引 |
| IO 高 | buffer pool 太小 |
| 连接暴涨 | 连接未释放 |
| 内存爆 | buffer pool 过大 |
innodb_buffer_pool_size=10G
innodb_log_file_size=1G
max_connections=500
slow_query_log=1
long_query_time=1
如果你愿意,可以告诉我:
我可以给你 定制化的 my.cnf 配置。