Redis 結合 Docker 搭建哨兵+主從,并整合SpringBoot
軟件版本
Redis 7.2.5
Docker 26.1.3
準備工作
由于docker直接拉取運行了,所以需要提前準備配置文件
Index of /releases/ (redis.io)
下載后,把redis-7.2.5.tar.gz\redis-7.2.5.tar\redis-7.2.5\里的
redis.conf
sentinel.conf
復制出來
概覽

結構如上圖所示,準備6個服務器。
配置哨兵節點
1.創建 redis-sentinel 目錄
2.創建 redis-sentinel/docker-compose.yml 文件
services:
redis-sentinel:
image: redis:7.2.5
ports:
- "26379:26379"
volumes:
- ./data:/data
restart: always
command: redis-sentinel /data/sentinel.conf
3.創建 redis-sentinel/data 目錄
4.配置文件復制到 redis-sentinel/data/sentinel.conf
5.添加/覆蓋配置項
logfile "/data/redis.log"
sentinel monitor mymaster <主節點IP> 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel auth-pass mymaster abc123
#這個是 Docker 關鍵配置,不然發給其他哨兵的是容器內部ip:
sentinel announce-ip <當前哨兵節點IP>
6.在三個哨兵節點分別執行上述5個步驟
配置主從節點
1.創建 redis 目錄
2.創建 redis/docker-compose.yml 文件
services:
redis:
image: redis:7.2.5
ports:
- "6379:6379"
volumes:
- ./data:/data
restart: always
command: redis-server /data/redis.conf
3.創建 redis/data 目錄
4.配置文件復制到 redis/data/redis.conf
5.添加/覆蓋配置項
#注釋掉這項:
#bind 127.0.0.1 -::1
logfile "/data/redis.log"
masterauth abc123
requirepass abc123
#這個僅配置到從節點:
replicaof <主節點IP> 6379
6.在主從節點分別執行上述5個步驟
啟動順序
1.啟動主節點
cd 到 redis 目錄,執行 docker compose up -d
2.啟動從節點
cd 到 redis 目錄,執行 docker compose up -d
3.啟動哨兵節點
cd 到 redis-sentinel 目錄,執行 docker compose up -d
整合SpringBoot
1.添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.添加配置
spring:
data:
redis:
password: abc123
sentinel:
master: mymaster
nodes:
- <哨兵1節點IP>:26379
- <哨兵2節點IP>:26379
- <哨兵3節點IP>:26379
3.配置讀寫分離
不建議配,除非主節點壓力很大,主節點新數據更新到從節點需要時間,這段時間會出現數據不一致。
@Configuration
public class RedisConfig {
@Bean
public LettuceClientConfigurationBuilderCustomizer clientConfigurationBuilderCustomizer() {
return builder -> builder.readFrom(ReadFrom.REPLICA_PREFERRED);
}
}
4.完成,可直接使用 RedisTemplate
參考資料
High availability with Redis Sentinel | Docs
浙公網安備 33010602011771號