簡介
Redis 是用 C 語言開發的一個開源的高性能鍵值對(key-value)數據庫。它通過提供多種鍵值數據類型來適應不同場景下的存儲需求,目前爲止 Redis 支持的鍵值數據類型如下:
- 字符串類型
- 散列類型
- 列表類型
- 集合類型
- 有序集合類型
Redis HA 方案
HA(High Available,高可用性羣集)機集羣系統簡稱,是保證業務連續性的有效解決方案,一般有兩個或兩個以上的節點,且分爲活動節點及備用節點。通常把正在執 行業務的稱爲活動節點,而作爲活動節點的一個備份的則稱爲備用節點。當活動節點出現問題,導致正在運行的業務(任務)不能正常運行時,備用節點此時就會偵測到,並立即接續活動節點來執行業務。從而實現業務的不中斷或短暫中斷。
Redis 一般以主/從方式部署(這裏討論的應用從實例主要用於備份,主實例提供讀寫)該方式要實現 HA 主要有如下幾種方案:
- keepalived: 通過 keepalived 的虛擬 IP,提供主從的統一訪問,在主出現問題時, 通過 keepalived
運行腳本將從提升爲主,待主恢復後先同步後自動變爲主,該方案的好處是主從切換後,應用程序不需要知道(因爲訪問的虛擬 IP
不變),壞處是引入 keepalived 增加部署複雜性,在有些情況下會導致數據丟失 - zookeeper: 通過 zookeeper 來監控主從實例, 維護最新有效的 IP, 應用通過 zookeeper 取得 IP,對
Redis 進行訪問,該方案需要編寫大量的監控代碼 - sentinel: 通過 Sentinel 監控主從實例,自動進行故障恢復,該方案有個缺陷:因爲主從實例地址( IP & PORT
)是不同的,當故障發生進行主從切換後,應用程序無法知道新地址,故在 Jedis2.2.2 中新增了對 Sentinel 的支持,應用通過
redis.clients.jedis.JedisSentinelPool.getResource() 取得的 Jedis
實例會及時更新到新的主實例地址
搭建 Redis 集羣
version: '3.1'
services:
master:
image: redis
container_name: redis-master
ports:
- 6379:6379
slave1:
image: redis
container_name: redis-slave-1
ports:
- 6380:6379
command: redis-server --slaveof redis-master 6379
slave2:
image: redis
container_name: redis-slave-2
ports:
- 6381:6379
command: redis-server --slaveof redis-master 6379
搭建 Sentinel 集羣(哨兵)
version: '3.1'
services:
sentinel1:
image: redis
container_name: redis-sentinel-1
ports:
- 26379:26379
command: redis-sentinel /usr/local/etc/redis/sentinel.conf
volumes:
- ./sentinel1.conf:/usr/local/etc/redis/sentinel.conf
sentinel2:
image: redis
container_name: redis-sentinel-2
ports:
- 26380:26379
command: redis-sentinel /usr/local/etc/redis/sentinel.conf
volumes:
- ./sentinel2.conf:/usr/local/etc/redis/sentinel.conf
sentinel3:
image: redis
container_name: redis-sentinel-3
ports:
- 26381:26379
command: redis-sentinel /usr/local/etc/redis/sentinel.conf
volumes:
- ./sentinel3.conf:/usr/local/etc/redis/sentinel.conf
修改 Sentinel 配置文件
Sentinel 集羣啓動了幾個就要修改幾個配置文件,這裏我們啓動了3個,需要三份 sentinel.conf 配置文件,分別爲 sentinel1.conf,sentinel2.conf,sentinel3.conf,配置文件內容相同
port 26379
dir /tmp
# 自定義集羣名,其中 192.168.55.128 爲虛擬機 redis-master 的 ip,6379 爲 redis-master 的端口,2 爲最小投票數(因爲有 3 臺 Sentinel 所以可以設置成 2)
sentinel monitor mymaster 192.168.55.128 6379 2
sentinel down-after-milliseconds mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 180000
sentinel deny-scripts-reconfig yes
啓動查看集羣是否生效
docker exec -it redis-sentinel-1 /bin/bash
redis-cli -p 26379
sentinel master mymaster
sentinel slaves mymaster