在 CentOS 上做 Redis 配置优化,一般从 操作系统层 + Redis 配置层 + 架构层 三个维度来做。下面给你一套生产环境常用优化方案,按优先级整理,适合大多数场景。
Redis 官方强烈建议关闭 THP,否则会导致延迟抖动。
# 查看
cat /sys/kernel/mm/transparent_hugepage/enabled
# 临时关闭
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
# 永久关闭(CentOS 7)
echo "echo never > /sys/kernel/mm/transparent_hugepage/enabled" >> /etc/rc.d/rc.local
echo "echo never > /sys/kernel/mm/transparent_hugepage/defrag" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
Redis 连接多时会用到。
ulimit -n
推荐设置:
# 临时
ulimit -n 65535
# 永久(CentOS 7)
vim /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
vim /etc/sysctl.conf
vm.swappiness = 1
vm.overcommit_memory = 1
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
生效:
sysctl -p
✅ overcommit_memory=1 避免 bgsave 时 fork 失败
✅ swappiness=1 防止 Redis 被 swap
路径一般:
/etc/redis.conf或/etc/redis/redis.conf
maxmemory 8gb
maxmemory-policy allkeys-lru
常用策略:
| 策略 | 说明 |
|---|---|
noeviction |
不淘汰(写失败) |
allkeys-lru |
所有 key LRU |
volatile-lru |
过期 key LRU |
allkeys-random |
随机淘汰 |
✅ 缓存场景推荐:allkeys-lru
save 900 1
save 300 10
save 60 10000
或关闭(纯缓存):
save ""
appendonly yes
appendfsync everysec
| 模式 | 性能 | 安全 |
|---|---|---|
| always | 低 | 高 |
| everysec ✅ | 中 | 中 |
| no | 高 | 低 |
✅ 推荐:appendfsync everysec
tcp-backlog 65535
timeout 0
tcp-keepalive 60
maxclients 10000
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command SHUTDOWN ""
systemctl restart redis
systemctl enable redis
✅ 避免:
KEYS *)查看慢日志:
redis-cli slowlog get 10
redis-server --version
开启 IO 多线程(CPU 多核):
io-threads-do-reads yes
io-threads 4
| 场景 | 推荐 |
|---|---|
| 高可用 | 主从 + Sentinel |
| 大数据量 | Redis Cluster |
redis-cli info memory
redis-cli info stats
redis-cli info replication
redis-cli info cpu
bind 0.0.0.0
port 6379
maxmemory 16gb
maxmemory-policy allkeys-lru
appendonly yes
appendfsync everysec
tcp-backlog 65535
timeout 0
tcp-keepalive 60
maxclients 10000
io-threads 4
io-threads-do-reads yes
redis-cli info 输出你可以直接贴:
Redis 版本 + 内存 + QPS + 是否持久化 + 业务场景