redis 一主三從三哨兵 每個從機和每個哨兵都是不一樣的端口 先啟用主機 在啟動從機 (windows下)(主機可寫可讀)(從機隻能讀不能寫)
複制三個redis檔案夾(從機)(檔案名redis+端口号):
每個從機中需要複制 redis的啟動exe檔案和配置檔案 (redis-server.exe , redis.windows.conf)
redis.windows.conf 需要配置
port 6380 //設定從機的端口,不能和主機的端口相同
slaveof 127.0.0.1 6379 //從機綁定主機
bat檔案啟動從機: redis-server.exe redis.windows.conf
哨兵(複制3個檔案夾)(檔案名sentinel+端口号)
每個哨兵中複制 redis的啟動exe檔案和配置檔案 (redis-server.exe ,sentinel.conf)
哨兵配置檔案(sentinel.conf):
bind 0.0.0.0
port 26379
sentinel monitor seckill 127.0.0.1 6379 1
sentinel down-after-milliseconds seckill 5000
sentinel failover-timeout seckill 15000
bat檔案啟動哨兵:redis-server.exe sentinel.conf --sentinel
哨兵在主服務當掉後,會從從服務中選取一個當成主服務
操作redis叢集類;
class RedisSentinel
{
public $redis;
public $master;
public $slaver;
public function __construct()
{
$this->master = new \Redis();
$this->slaves = new \Redis();
$this->_connect();
}
private function _connect()
{
$redis = new \Redis();
$host = '127.0.0.1';
//連結sentinel服務,host為ip,port為端口
$port = ['6379','6380'];
foreach($port as $k=>$v){
if($redis->connect($host,$v)){
$this->redis=$redis;
$master[] = $this->parseArrayResult($redis->rawCommand('SENTINEL','master','seckill'));
$slaves = $redis->rawCommand('SENTINEL','slaves','seckill');
$slavesIndex = array_rand($slaves);//擷取數組的鍵
$slaves = $this->parseArrayResult($slaves[$slavesIndex]);
$this->parseArrayResult($this->slaves)
break;
}
}
//master是主服務,在其他的方法中引入後可直接調用;連結redis
$this->master->$redis->connect($master['ip'],$master['port']);
//slave是從服務
$this->slaver->$redis->connect($slaves['ip'],$slaves['port']);
}
//這個方法可以将以上sentinel傳回的資訊解析為數組
function parseArrayResult(array $data)
{
$result = array();
$count = count($data);
for ($i = 0; $i < $count;) {
$record = $data[$i];
if (is_array($record)) {
$result[] = parseArrayResult($record);
$i++;
} else {
$result[$record] = $data[$i + 1];
$i += 2;
}
}
return $result;
}
public function setRedisCahe($key,$value,$time=600)
{
$this->master->set($key,$value,$time);
}
public function getRedisCahe($key)
{
$this->slaver->get($key);
}
}