在 CentOS 上优化 Redis 配置,通常从操作系统层面、Redis 配置文件、内存与持久化策略、集群与高可用几个维度来做。下面给你一套比较实用、可落地的优化建议(基于 CentOS 7/8 + Redis 5/6/7)。
Redis 官方明确建议关闭 THP,否则会造成延迟抖动。
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
永久生效(CentOS):
# /etc/rc.d/rc.local
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
chmod +x /etc/rc.d/rc.local
Redis 连接数多时需要。
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
# /etc/sysctl.conf
vm.overcommit_memory = 1
net.core.somaxconn = 1024
net.ipv4.tcp_max_syn_backlog = 8192
生效:
sysctl -p
vm.overcommit_memory=1可避免 bgsave 时 OOM
bind 0.0.0.0
port 6379
protected-mode no # 生产建议用防火墙+密码
maxmemory 8gb
maxmemory-policy allkeys-lru
常见策略:
allkeys-lru:通用缓存volatile-lru:只淘汰带 TTL 的 keynoeviction:写满直接报错(不推荐)save 900 1
save 300 10
save 60 10000
如果纯缓存:
save ""
appendonly yes
appendfsync everysec
always太慢,no不安全,生产用everysec
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
slowlog-log-slower-than 10000
slowlog-max-len 128
io-threads 4
io-threads-do-reads yes
只对网络 IO 有效,命令执行仍是单线程
lua-time-limit 5000
requirepass yourstrongpassword
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command KEYS ""
redis-cli info memory
redis-cli info stats
redis-cli info persistence
redis-cli --bigkeys
redis-cli info memory | grep mem_fragmentation_ratio
大于 1.5 考虑重启或
activedefrag
maxmemory 8gb
maxmemory-policy allkeys-lru
save ""
appendonly no
io-threads 4
如果你愿意,可以告诉我:
我可以直接帮你出一份可复制的 redis.conf 模板。