Master可能会因为某些情况宕机了,如果在客户端是固定一个地址去访问,肯定是不合理的,所以客户端请求是请求哨兵,从哨兵获取主机地址的信息,或者是从机的信息。可以实现一个例子
1、随机选择一个哨兵连接,获取主机、从机信息
2、模拟客户端定时访问,实现简单轮训效果,轮训从节点
3、连接失败重试访问
vim client.php
include 'Round.php';
$sentinelConf=[
['ip'=>'192.168.11.43','port'=>22530],
['ip'=>'192.168.11.43','port'=>22531],
['ip'=>'192.168.11.43','port'=>22532]
];
//随机访问
$sentinelInfo=$sentinelConf[array_rand($sentinelConf)];
$redis=new Redis();
$redis->connect($sentinelInfo['ip'],$sentinelInfo['port']);
//获取redis-slave 从节点信息
$slavesInfo=$redis->rawCommand('SENTINEL','slaves','mymaster');
$slaves=[];
foreach ($slavesInfo as $val){
$slaves[]=['ip'=>$val[3],'port'=>$val[5]];
}
//加载到缓存当中,可以记录这次访问的时间跟上次的访问时间
//模拟客户端访问
swoole_timer_tick(600,function () use($slaves) {
//轮训
$slave=(new Round())->select($slaves);
try{
$redis=new Redis();
$redis->connect($slave['ip'],$slave['port']);
var_dump($slave,$redis->get('peter'));
}catch (\RedisException $e){
}
});
vim Round.php
class Round{
static $lastIndex=0;
public function select($list){
$currentIndex=self::$lastIndex; //当前的index
$value=$list[$currentIndex];
if($currentIndex+1>count($list)-1){
self::$lastIndex=0;
}else{
self::$lastIndex++;
}
return $value;
}
}