1.新建一個mkdir redis-sentinel文件夾
進入項目文件夾 cd redis-sentinel,再建立一個sentinel專門來存放哨兵腳本,然后cd sentinel
建立sentinel.conf配置文件:
sentinel monitor mymaster redis-master 6379 2 sentinel down-after-milliseconds mymaster 5000 sentinel parallel-syncs mymaster 1 sentinel failover-timeout mymaster 5000
該配置的意思是,監控主服務器的6379端口並且起兩個實例,如果哨兵5s內沒有收到主節點的心跳,哨兵就認為主節點宕機了,默認是30秒,如果5秒以上連接不上主庫同步,則在5秒后進行選舉,對其他的從服務器進行角色轉換
2.建立sentinel-entrypoint.sh腳本文件
#!/bin/sh sed -i "s/$SENTINEL_QUORUM/$SENTINEL_QUORUM/g" /etc/redis/sentinel.conf sed -i "s/$SENTINEL_DOWN_AFTER/$SENTINEL_DOWN_AFTER/g" /etc/redis/sentinel.conf sed -i "s/$SENTINEL_FAILOVER/$SENTINEL_FAILOVER/g" /etc/redis/sentinel.conf exec docker-entrypoint.sh redis-server /etc/redis/sentinel.conf --sentinel
該腳本文件會對配置文件進行同步,用來啟動哨兵
3.建立Dockerfile
建立Dockerfile指定基礎鏡像,同時拷貝配置文件到鏡像內部:
FROM redis EXPOSE 26379 ADD sentinel.conf /etc/redis/sentinel.conf RUN chown redis:redis /etc/redis/sentinel.conf COPY sentinel-entrypoint.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/sentinel-entrypoint.sh ENTRYPOINT ["sentinel-entrypoint.sh"]
4.建立docker-compose.yml配置文件
master:
image: redis
ports:
- "6379:6379"
slave1:
image: redis
command: redis-server --slaveof redis-master 6379
links:
- master:redis-master
ports:
- "6380:6379"
slave2:
image: redis
command: redis-server --slaveof redis-master 6379
links:
- master:redis-master
ports:
- "6381:6379"
sentinel1:
build: sentinel
environment:
- SENTINEL_DOWN_AFTER=5000
- SENTINEL_FAILOVER=5000
links:
- master:redis-master
- slave1
sentinel2:
build: sentinel
environment:
- SENTINEL_DOWN_AFTER=5000
- SENTINEL_FAILOVER=5000
links:
- master:redis-master
- slave2
意思是,我們起三台redis服務,分別跑在6379,6380,6381 ,一主兩從,並且有兩個哨兵實例來監控他們,最后項目結構是這樣的
5.在項目根目錄下,啟動服務:
docker-compose up --force-recreate
6.測試同步
分別開三個窗口登錄到redis,redis-cli -p 6379,redis-cli -p 6380,redis-cli -p 6381
在主庫6379中set 123 123,然后分別在從庫get 123
7.測試哨兵模式是否好用
docker stop redissentinel_master_1
此時主庫已經連接不上了,進入從庫,使用info命令來查看從庫的角色
發現之前6380本來是從庫(slave)角色,現在已經變成主庫了(master)了。
這就是所謂的高負載高可用架構,在使用集群承擔高負載的同時,也能進行高可用的容災機制。