温馨提示×

怎样优化CentOS Redis

小樊
58
2026-08-29 18:15:45
栏目: 云计算

下面按生产环境常见做法,从 系统、Redis 配置、内存、持久化、安全、监控 几个方面,系统说明 如何优化 CentOS 上的 Redis。


一、系统层面优化(CentOS)

1. 关闭 THP(透明大页)

Redis 官方强烈建议关闭 THP,否则会造成延迟抖动。

echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag

开机自动关闭:

vi /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

2. 调整 ulimit

避免 “max number of clients reached” 错误。

vi /etc/security/limits.conf

添加:

* soft nofile 65535
* hard nofile 65535

3. 调整 TCP backlog

vi /etc/sysctl.conf

追加:

net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
vm.overcommit_memory = 1

立即生效:

sysctl -p

二、Redis 核心配置优化(redis.conf)

1. 绑定与端口

bind 0.0.0.0   # 生产环境建议指定 IP
port 6379

2. 最大内存限制(非常重要)

避免把系统内存吃完。

maxmemory 4gb
maxmemory-policy allkeys-lru

常用策略:

策略 说明
volatile-lru 只淘汰设置过期时间的 key
allkeys-lru 所有 key LRU
noeviction 不淘汰(写失败)

3. 持久化优化(RDB + AOF)

✅ 推荐方案(生产常用)

save 900 1
save 300 10
save 60 10000

appendonly yes
appendfsync everysec

⚠️ 不建议:

appendfsync always   # 太慢

4. 关闭不必要的功能

# 如果不用,关闭
replicaof no one

5. 后台运行 & 日志

daemonize yes
loglevel notice
logfile /var/log/redis/redis.log

三、内存与性能优化

1. 使用 Hash、ZSet 等紧凑结构

避免大量小 key:

user:1:name
user:1:age

✅ 改为:

user:1 => {name, age}

2. 设置合理的过期时间

EXPIRE key 3600

3. 避免大 Key

redis-cli --bigkeys

建议:

  • String < 10KB
  • Set / Hash < 5000 元素

四、主从 / 集群优化(如有)

1. 主从复制

replicaof 192.168.1.10 6379

建议:

  • 主节点不持久化
  • 从节点开启 AOF

2. 集群模式

redis-cli --cluster create

注意:

  • 至少 3 主 3 从
  • 每个主节点负责一部分 slot

五、安全优化(非常重要)

1. 设置密码

requirepass StrongPassword123

连接:

redis-cli -a StrongPassword123

2. 禁止外网直接访问

bind 127.0.0.1

或使用防火墙:

firewall-cmd --permanent --add-port=6379/tcp
firewall-cmd --reload

六、监控与维护

1. 查看性能

redis-cli info
redis-cli info memory
redis-cli info stats

2. 慢查询

slowlog-log-slower-than 10000
slowlog-max-len 128

查看:

redis-cli slowlog get

3. 常用监控指标

  • 内存使用率
  • 命中率(keyspace_hits / misses)
  • 连接数
  • 延迟

七、CentOS 7/8 systemd 示例

[Unit]
Description=Redis
After=network.target

[Service]
ExecStart=/usr/local/bin/redis-server /etc/redis.conf
Restart=always

[Install]
WantedBy=multi-user.target

八、推荐生产典型配置(示例)

maxmemory 8gb
maxmemory-policy allkeys-lru
appendonly yes
appendfsync everysec
save 900 1
requirepass xxx
bind 0.0.0.0

如果你愿意,可以告诉我:

  • ✅ Redis 版本
  • ✅ CentOS 版本
  • ✅ 数据量 / QPS
  • ✅ 是否主从 / 集群

我可以直接帮你 定制一份最优 redis.conf。

0 踩