Redis Sentinel(哨兵)是一種用于管理 Redis 實例的高可用性解決方案。它提供了監控、通知和自動故障轉移等功能,確保 Redis 服務在發生故障時能夠自動恢復,提供高可用性和可靠性。以下是詳細介紹 Redis Sentinel 的功能及其代碼示例。
Redis Sentinel 的功能
-
監控(Monitoring):
- Sentinel 會持續監控主節點和從節點的運行狀態,檢查它們是否正常工作。
-
通知(Notification):
- 如果 Sentinel 檢測到某個節點發生故障,它會通過 API 向系統管理員或其他應用程序發送通知。
-
自動故障轉移(Automatic Failover):
- 如果主節點發生故障,Sentinel 會將其中一個從節點提升為新的主節點,并將其他從節點指向新的主節點。
-
配置提供者(Configuration Provider):
- Sentinel 允許客戶端應用程序查詢當前 Redis 集群的狀態信息,以便客戶端能夠始終連接到正確的主節點。
Sentinel 配置示例
1. 配置 Redis 實例
配置主從架構的 Redis 實例。
主節點配置(master.conf):
port 6379
bind 127.0.0.1
dir /var/lib/redis
appendonly yes
從節點配置(slave.conf):
port 6380
bind 127.0.0.1
dir /var/lib/redis
appendonly yes
slaveof 127.0.0.1 6379
啟動主從節點:
redis-server master.conf
redis-server slave.conf
2. 配置和啟動 Sentinel
創建 Sentinel 配置文件(sentinel.conf):
port 26379
dir /tmp
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 60000
啟動 Sentinel:
redis-sentinel sentinel.conf
3. Java 代碼示例:使用 Jedis 連接帶有 Sentinel 的 Redis 集群
以下 Java 代碼展示了如何使用 Jedis 庫連接和操作帶有 Sentinel 的 Redis 集群。
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.HostAndPort;import java.util.HashSet;
import java.util.Set;public class RedisSentinelExample {public static void main(String[] args) {// 定義 Sentinel 節點Set<String> sentinels = new HashSet<>();sentinels.add("127.0.0.1:26379");// 創建 JedisSentinelPool 對象JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels);try (Jedis jedis = pool.getResource()) {// 操作 Redisjedis.set("key", "value");String value = jedis.get("key");System.out.println("Get key: " + value);} finally {// 關閉連接池pool.close();}}
}
詳細解釋
-
監控:
- Sentinel 持續監控主節點和從節點的運行狀態。配置文件中的
sentinel monitor mymaster 127.0.0.1 6379 2
表示 Sentinel 監控的主節點是127.0.0.1:6379
,并且至少需要 2 個 Sentinel 同意主節點失效,才會進行故障轉移。
- Sentinel 持續監控主節點和從節點的運行狀態。配置文件中的
-
通知:
sentinel down-after-milliseconds mymaster 5000
配置了 Sentinel 判斷主節點失效的時間閾值(毫秒)。超出這個時間后,Sentinel 會認為主節點失效并發送通知。
-
自動故障轉移:
sentinel failover-timeout mymaster 60000
配置了 Sentinel 進行故障轉移的超時時間。故障轉移過程中,Sentinel 會將其中一個從節點提升為新的主節點,并將其他從節點指向新的主節點。
-
配置提供者:
- 客戶端應用程序(如 Java 代碼中的
JedisSentinelPool
)可以通過 Sentinel 獲取當前主節點的信息,并確保連接的是正確的主節點。
- 客戶端應用程序(如 Java 代碼中的
故障轉移的示例
為了測試自動故障轉移,您可以強制關閉 Redis 主節點,觀察 Sentinel 的行為。
# 停止 Redis 主節點
redis-cli -p 6379 shutdown
此時,Sentinel 會檢測到主節點失效,并自動提升從節點為新的主節點,然后重新配置集群。
總結
Redis Sentinel 提供了一種高可用性解決方案,通過監控、通知、自動故障轉移和配置提供等功能,確保 Redis 服務的可靠性。通過配置 Sentinel 和使用 Jedis 庫,客戶端應用程序可以方便地連接和操作帶有 Sentinel 的 Redis 集群,從而實現高可用性和自動故障恢復。