Redis 以單線程事件循環實現百萬級 QPS,但生產環境若忽視持久化策略、內存淘汰、主從一致性、網絡安全、監控告警,極易演變成線上事故。本文提供**從源碼編譯到高可用集群**的標準化部署 SOP,並附帶核心參數調優表、故障排查決策樹、監控儀表板關鍵指標。
vm.overcommit_memory = 1 # 允許過度提交內存,防止 fork 失敗
net.core.somaxconn = 65535 # 完整連接隊列長度,配合 tcp-backlog
net.ipv4.tcp_max_syn_backlog = 65535
vm.swappiness = 0 # 避免 swap,Redis 對延遲極敏感
fs.file-max = 1000000 # 系統級文件句柄上限
sysctl --system
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
# 永久生效:加入 /etc/rc.local 或 systemd 服務
useradd -r -s /sbin/nologin -M redis
mkdir -p /var/lib/redis /var/log/redis /etc/redis
chown redis:redis /var/lib/redis /var/log/redis
# /etc/security/limits.d/redis.conf
redis soft nofile 65535
redis hard nofile 65535
redis soft nproc 65535
redis hard nproc 65535
yum install -y gcc make tcl jemalloc-devel
wget https://download.redis.io/releases/redis-7.2.4.tar.gz
tar xzf redis-7.2.4.tar.gz && cd redis-7.2.4
make MALLOC=jemalloc # 使用 jemalloc 減少碎片
make install PREFIX=/usr/local/redis
# 複製配置模板
cp redis.conf /etc/redis/redis.conf
chown -R redis:redis /usr/local/redis /etc/redis /var/lib/redis /var/log/redis
| 參數 | 推薦值 | 核心影響 |
|---|---|---|
| bind | 127.0.0.1 10.0.1.5 | 僅綁定內網 IP,拒絕公網訪問 |
| port | 6379 (建議改隨機高位端口) | 減少掃描攻擊面 |
| daemonize | yes | 守護進程模式 |
| pidfile | /var/run/redis/redis.pid | systemd 管理依賴 |
| loglevel | notice | 生產環境平衡日誌量與可觀測性 |
| logfile | /var/log/redis/redis.log | 持久化日誌,配合 logrotate |
| databases | 16 (默認) | 多 DB 特性建議棄用,改用 Key 前綴隔離 |
| requirepass | 強密碼 (AES-256 加密存儲) | ACL 認證,Redis 6+ 支持細粒度用戶權限 |
| maxmemory | 物理內存 70-80% | 防 OOM Kill,必須配合策略 |
| maxmemory-policy | allkeys-lru | 淘汰策略:LRU 淘汰所有鍵,適合緩存場景 |
| save | 900 1 / 300 10 / 60 10000 | RDB 快照頻率,高寫入場景建議關閉 (save "") 依賴 AOF |
| appendonly | yes | 開啟 AOF,數據零丟失 (everysec 最多丟 1 秒) |
| appendfsync | everysec | 性能與安全平衡點 |
| aof-use-rdb-preamble | yes | 混合持久化,重啟恢復快 10 倍 |
| lazyfree-lazy-eviction | yes | 異步釋放內存,避免大鍵刪除阻塞主線程 |
| slowlog-log-slower-than | 10000 (10ms) | 慢查詢閾值,微秒單位 |
| slowlog-max-len | 128 | 慢查詢記錄條數 |
| tcp-backlog | 511 | 配合 somaxconn |
| timeout | 0 (不斷開空閒連接) | 按業務調整,防連接泄漏可設 300s |
| maxclients | 10000 | 配合 ulimit -n |
cat > /etc/systemd/system/redis.service <<'EOF'
[Unit]
Description=Redis In-Memory Data Store
After=network.target
[Service]
Type=forking
User=redis
Group=redis
ExecStart=/usr/local/redis/bin/redis-server /etc/redis/redis.conf
ExecStop=/usr/local/redis/bin/redis-cli -a $REDIS_PASSWORD shutdown
ExecReload=/bin/kill -USR2 $MAINPID
PIDFile=/var/run/redis/redis.pid
Restart=on-failure
RestartSec=5
LimitNOFILE=65535
LimitNPROC=65535
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now redis
systemctl status redis
replicaof 10.0.1.5 6379
masterauth master_password
replica-read-only yes
repl-diskless-sync yes # 無磁盤同步,避免主節點磁盤 IO 爭搶
repl-diskless-sync-delay 5 # 等待更多從節點加入再發送
port 26379
daemonize yes
logfile /var/log/redis/sentinel.log
dir /var/lib/redis/sentinel
sentinel monitor mymaster 10.0.1.5 6379 2 # quorum=2
sentinel auth-pass mymaster master_password
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
部署 **3+ Sentinel 節點**,客戶端使用 StackExchange.Redis / Lettuce / Jedis 內建 Sentinel 支持自動發現主節點。
# 6 節點示例:3 主 3 從
for port in 7000 7001 7002 7003 7004 7005; do
mkdir -p /etc/redis/cluster/$port /var/lib/redis/cluster/$port
cat > /etc/redis/cluster/$port/redis.conf <
| 結構 | 典型場景 | 核心命令 | 內存優化 |
|---|---|---|---|
| String | 緩存對象(JSON)、計數器、分布式鎖、Session | SET/GET/INCR/DECR/SETNX/SETEX | 小對象用 Hash 合併 (Redis 4.0+ 內部優化) |
| Hash | 用戶資料、商品屬性、購物車、單點登錄 Token 映射 | HSET/HGET/HMGET/HGETALL/HINCRBY | ziplist/listpack 壓縮編碼 (hash-max-ziplist-entries/value) |
| List | 消息隊列、最新動態、分頁緩存 | LPUSH/RPOP/LRANGE/LTRIM | 長列表定期 LTRIM 截斷 |
| Set | 標籤、共同好友、抽獎池、IP 白名單 | SADD/SREM/SISMEMBER/SINTER/SUNION/SDIFF | intset 編碼 (全整數且 < 512 元素) |
| Sorted Set | 排行榜、延遲隊列、按時間範圍查詢、速率限制 | ZADD/ZRANGE/ZRANGEBYSCORE/ZINCRBY/ZREM | skiplist + dict 結構,分數相同按字典序 |
數據重要性
│
├─ 可丟失 (純緩存) → 關閉持久化 (save "", appendonly no) → 性能最高
│
├─ 秒級可接受丟失 → 僅 AOF everysec (appendonly yes, appendfsync everysec)
│
└─ 零數據丟失 → AOF always (fsync 每寫) + 備份腳本
(性能損失 30-50%,極少數金融場景)
最佳實踐:緩存場景 **RDB 關閉 + AOF everysec + 混合持久化**;關鍵業務 **AOF always + 異地備份**。
redis_up, role (master/replica)instantaneous_ops_per_sec, rejected_connections, blocked_clientsused_memory, used_memory_rss, mem_fragmentation_ratio (>1.5 告警), maxmemoryrdb_last_save_time, aof_last_rewrite_time_sec, aof_current_sizemaster_link_status, replica_lag (秒), connected_slavesexpired_keys, evicted_keys, keyspace_hits/missesslowlog 大鍵操作 / bigkeys / THP 未關 / swap 發生 / 主從全量同步佔用帶寬。maxmemory 未生效 / 淘汰策略錯誤 / 大量大鍵未釋放 / 內存碎片率高 → MEMORY PURGE / 重啟。repl-backlog-size (默認 1MB → 100MB) / repl-timeout / 無磁盤同步。rdb-save-incremental-fsync yes。Redis 部署是系統工程,而非單純安裝軟件。**內核參數、內存策略、持久化模式、高可用拓撲、監控體系**五大支柱缺一不可。建議將本文配置模板納入基礎設施即代碼 (IaC) 倉庫,通過 Ansible/Terraform 實現版本化、可複現、可審計的交付流程。