天天看點

高可用筆記(2)redis首先安裝Redisredis單例redis高可用redis開啟成功redis.conf的最後多了這樣一行配置,說明host1已經是host2的slave了。

redis是一種key-value型資料庫,基于記憶體,也可持久化,速度非常快。常用于做緩存。

安裝

安裝完畢,看看是否安裝成功

建立一個存放redis配置檔案的目錄

拷貝一個redis.conf檔案:

redis.conf配置檔案的幾個重要屬性:

啟動redis-server

檢視是否啟動成功

redis-cli

redis單例試驗完成。

redis的高可用方案通常有sentinel和twemproxy,sentinel是redis自帶的功能,這裡我們選着用sentinel。

測試環境

redis高可用至少需要三台主機。

host1 192.168.30.1 #主節點master,可讀寫

host2 192.168.30.2 #從節點slave,同步資料,隻讀不寫

host3 192.168.30.3 #從節點slave,同步資料,隻讀不寫

配置主從關系

首先,host2和host3一樣安裝redis。

其次,修改host2和host3的配置檔案如下:

最後,重新開機host2和host3的redis-server後,三台redis-server的主從關系已經建立。

在host2或host3上運作測試可以看到:

設定sentinel

上一步中已經配置了3個redis-server的主從關系,master寫入的資料會同步到兩個slave。此時如果host1當機,host2和host3無法寫入資料,那麼我們就需要将host2、host3中優先級高的那台提升為master。這就需要設定sentinel(哨兵)來監聽redis-server,當sentinel判斷主節點down的時候,sentinel會将其中一個slave提升為master。

在host1、host2、host3中各建立一個配置檔案,内容相同,如下

/etc/redis/sentinel.conf

sentinel主觀地判斷mymaster當機(sdown)的時候不會立即failover主從切換,它需要再次确認,客觀地認為mymaster當機(odown)後,才會自動進行主從切換。

odown,即objectively down,當sentinel認為mymaster主觀當機(sdown)時,會發起一個投票,之後當多數sentinel判斷mymaster已經當機時,才會得出結果odown。那麼這裡判斷mymaster odown時就必須有兩台sentinel投贊成票。這也是redis高可用至少需要3台主機的原因。

開啟三個sentinel

這是再看一下sentinel.conf:

ha測試

第一種情況,host2或host3當機,這時master是active的,是以沒有任何問題。

第二種情況,host1當機,host2-sentinel和host3-sentinel會判斷host1為odown,按照優先級host2被提升為master。

我們來模拟這個過程。

kill掉host1的redis-server和redis-sentinel程序:

等待幾秒後,看一下host2的redis-server

$ redis-server /etc/redis/redis.conf

$ redis-sentinel /etc/redis/sentinel.conf

$ ps -aux | grep redis

root 11371 0.0 0.3 136920 7536 ? ssl 04:45 0:04 redis-server 0.0.0.0:6379

root 12763 0.0 0.4 136916 7672 ? ssl 06:35 0:00 redis-sentinel 0.0.0.0:7000 [sentinel]

$ cat /etc/redis/redis.conf

……

slaveof 192.168.30.2 6379