前言:在哨兵服务搭建的redis主从缓存使用php连接的方式不是直接去连redis地址,而是连接哨兵服务,通过哨兵获取到redis当前主服务器。
相关知识:predis, redis, Sentinel
1、建一个Sentinel使用类,或者使用predis类库:
<?php
/**
* redis php哨兵的使用
* User:
* Date: 2019/7/1
* Email:
*/
class Sentinel
{
private $connection;
public function __construct()
{
$this->connection=[];
}
/**
* @param $host 地址
* @param $port 端口号
* @return bool|Redis
*/
private function connect($host,$port)
{
try{
$con = new Redis();
$res = $con->connect($host,$port);
if ($res){
return $con;
}
}catch (Exception $exception){
echo "error hosts:".$host." port:".$port."\n";
}
return false;
}
/**
* 连接Sentinel服务器,并把成功的链接写入数组记录
* @param $host
* @param $port
* @return bool
*/
public function setSentinel($host,$port)
{
$res = $this->connect($host,$port);
if ($res){
$this->connection[] = $res;
return true;
}
return false;
}
/**
* 通过Sentinel获取到正在连接的redis主服务,循环写入数组
* @return array
* @throws ErrorException
*/
public function getSentinel()
{
if (empty($this->connection)){
throw new ErrorException("sorry no connection");
}
$masterList=[];
foreach ($this->connection as $con){
$result = $con->rawCommand('SENTINEL', 'masters');;
list(,,,$host,,$port) = $result[0];
$masterList[] = [$host,$port];
}
return $masterList;
}
/**
* 返回一个可用的配置项
* @return mixed
* @throws ErrorException
*/
public function getMaster()
{
$list = $this->getSentinel();
return $list[0];
}
/**
* 获取redis主服务器配置并连接使用
* @return bool|Redis
* @throws ErrorException
*/
public function getConnection()
{
list($host,$port) = $this->getMaster();
return $this->connect($host,$port);
}
}
2、加载类库并使用:
<?php
/**
* redis 哨兵的php使用
* User:
* Date: 2019/6/27
* Email:
*/
require_once 'Redis_Sentinel.php';
class script_redis
{
private $redis;
public function __construct()
{
//初始化Sentinel对象
$redis = new Redis_Sentinel();
$redis->setSentinel('127.0.0.1',26379);
$redis->setSentinel('127.0.0.1',26380);
$redis->setSentinel('127.0.0.1',26381);
//获取redis主服务配置
$res = $redis->getMaster();
var_dump($res);
$this->redis = $redis->getConnection();
//查看连接是否正常
var_dump($this->redis->ping());
}
public function index()
{
//写入
$this->redis->set('afs',1234567);
//获取
$value = $this->redis->get('afs');
//打印
var_dump($value);
}
}
$a = new script_redis();
$a->index();
3、先开启主从redis 再开启哨兵监控
4、执行php文件:
5、现在来做点坏操作,停掉主redis服务
6、再来执行一下php文件看一下:
成功获取到了新的配置
7、再来一次这次停掉一个哨兵服务看一下。
8、看一下php的使用:
总结:在redis主从与哨兵搭配中,只要有一个哨兵服务与一个redis服务存活就可以正常工作。
redis与哨兵的搭建可以看这篇:https://blog.youkuaiyun.com/qq_24909089/article/details/93890583