一、设置内存限制和淘汰策略
修改当前配置(立刻生效)
# 连接到 Redis
redis-cli
# 设置最大内存为 1.5GB (适用于 4GB 内存服务器)
127.0.0.1:6379> CONFIG SET maxmemory 1610612736 # 1.5GB 的字节数
# 设置合理的淘汰策略(推荐)
127.0.0.1:6379> CONFIG SET maxmemory-policy allkeys-lru
# 验证配置
# 使用操作系统终端
redis-cli info memory | grep -E "maxmemory|maxmemory_policy"
修改配置文件(通常为 /etc/redis/redis.conf)(重启生效)
# 最大内存 1.5GB (4GB 服务器安全值)
maxmemory 1610612736
# 推荐淘汰策略
maxmemory-policy allkeys-lru
# 内存碎片整理配置(解决你的高碎片问题)
activedefrag yes
active-defrag-ignore-bytes 50mb
active-defrag-threshold-lower 20
active-defrag-threshold-upper 50
active-defrag-cycle-min 5
active-defrag-cycle-max 20
# 关闭透明大页(减少延迟)
disable-thp yes
备注:重启Redis
systemctl restart redis
二、其他配置
手动清理碎片
redis-cli memory purge
注意:需要 Redis 6.2+ 且支持 jemalloc。
mem_fragmentation_ratio表示碎片化。