php操作redis哨兵模式,主从切换后自动获取master

本文将介绍如何使用PHP来连接redis哨兵模式。哨兵模式:大概的原理就是监听redis主库心跳包,如果心跳断开,则枚举一个从库推举成为新的主库,防止redis宕机不能使用。为了增强redis的性能,防止其挂掉,引用redis哨兵监控redis集群是个不错的选择。下面三步简单记录php连接redis哨兵。 第一步、获取哨兵模式连接redis句柄对象

1/** 2 * 哨兵模式连接redis 3 * @return array|Redis 4 */ 5function im_cache_redis() { 6 global $_W; 7 static $im_redisobj; 8 $config = $_W['config']['im']['redis']; 9 10 //哨兵节点 11 $temp_data = [ 12 [ 13 'ip' => '192.168.101.85', 14 'port' => 26380 15 ], 16 [ 17 'ip' => '192.168.101.85', 18 'port' => 26381 19 ], 20 [ 21 'ip' => '192.168.101.85', 22 'port' => 26382 23 ] 24 ]; 25 26 $address = redis_nodeinfo($temp_data); 27 logging_run(__METHOD__ . ':redis哨兵获取主节点地址:' . json_encode($address),LOGGING_INFO); 28 $im_redisobj = new Redis(); 29 try { 30 $im_redisobj->connect($address['ip'],intval($address['port'])); 31 if (!empty($config['auth'])) { 32 $auth = $im_redisobj->auth($config['auth']); 33 } 34 } catch (Exception $e) { 35 logging_run(__METHOD__ . ':redis连接失败,错误信息:' . $e->getMessage(),LOGGING_ERROR); 36 return error(-1,'im redis连接失败,错误信息:'.$e->getMessage()); 37 } 38 return $im_redisobj; 39}

第二步、获取redis哨兵主节点地址

1/** 2 * 获取redis哨兵主节点地址 3 * @param array $temp_data 4 * @return array 5 */ 6function redis_nodeinfo($temp_data = []){ 7 $random = []; 8 $ips = []; 9 //哨兵节点 10 //$temp_data = [['ip'=>'101.36.149.73','port'=>263719],['ip'=>'101.36.149.41','port'=>26379],['ip'=>'101.36.149.189','port'=>26379]]; 11 for($count=1;$count<count($temp_data);$count++){ 12 $random[] =$count; 13 } 14 shuffle($random); 15 foreach($random as $key){ 16 $ips[$temp_data[$key]['ip']]=['port'=>$temp_data[$key]['port']]; 17 } 18 $sentinel = new Sentinel(); 19 foreach($ips as $ip=>$portinfo){ 20 try{ 21 $sentinel->connect($ip, $portinfo['port'],1); 22 $address = $sentinel->getMasterAddrByName('mymaster'); 23 if($address){ 24 echo '哨兵节点:' .$ip .'正常'. '<br/>'; 25 26 return $address; 27 } 28 }catch(Exception $e){ 29 echo '哨兵节点:' .$ip .'异常 异常信息:' . $e->getMessage() . '<br/>'; 30 } 31 } 32}

第三步、封装Sentinel类

1<?php 2 3class Sentinel 4{ 5 /** 6 * @var \Redis 7 */ 8 protected $redis; 9 10 public function __construct() 11 { 12 $this->redis = new Redis(); 13 } 14 15 public function __destruct() 16 { 17 try { 18 $this->redis->close(); 19 } catch (\Exception $e) { 20 } 21 } 22 23 /** 24 * @param $host 25 * @param int $port 26 * @return boolean 27 */ 28 public function connect($host, $port = 26379) 29 { 30 if (!$this->redis->connect($host, $port)) { 31 return false; 32 } 33 return true; 34 } 35 36 /** 37 * This command simply returns PONG. 38 * 39 * @return string STRING: +PONG on success. Throws a RedisException object on connectivity error. 40 */ 41 public function ping() 42 { 43 return $this->redis->ping(); 44 } 45 46 /** 47 * Show a list of monitored masters and their state. 48 * 49 * @return array 50 */ 51 public function masters() 52 { 53 return $this->parseArrayResult($this->redis->rawCommand('SENTINEL', 'masters')); 54 } 55 56 /** 57 * parse redis response data 58 * 59 * @param array $data 60 * @return array 61 */ 62 private function parseArrayResult(array $data) 63 { 64 $result = array(); 65 $count = count($data); 66 for ($i = 0; $i < $count;) { 67 $record = $data[$i]; 68 if (is_array($record)) { 69 $result[] = $this->parseArrayResult($record); 70 $i++; 71 } else { 72 $result[$record] = $data[$i + 1]; 73 $i += 2; 74 } 75 } 76 77 return $result; 78 } 79 80 /** 81 * Show the state and info of the specified master. 82 * 83 * @param string $master_name 84 * @return array 85 */ 86 public function master($master_name) 87 { 88 return $this->parseArrayResult($this->redis->rawCommand('SENTINEL', 'master', $master_name)); 89 } 90 91 /** 92 * Show a list of slaves for this master, and their state. 93 * 94 * @param string $master_name 95 * @return array 96 */ 97 public function slaves($master_name) 98 { 99 return $this->parseArrayResult($this->redis->rawCommand('SENTINEL', 'slaves', $master_name)); 100 } 101 102 /** 103 * Show a list of sentinel instances for this master, and their state. 104 * 105 * @param string $master_name 106 * @return array 107 */ 108 public function sentinels($master_name) 109 { 110 return $this->parseArrayResult($this->redis->rawCommand('SENTINEL', 'sentinels', $master_name)); 111 } 112 113 /** 114 * Return the ip and port number of the master with that name. 115 * If a failover is in progress or terminated successfully 116 * for this master it returns the address and port of the promoted slave. 117 * 118 * @param string $master_name 119 * @return array 120 */ 121 public function getMasterAddrByName($master_name) 122 { 123 $data = $this->redis->rawCommand('SENTINEL', 'get-master-addr-by-name', $master_name); 124 return array( 125 'ip' => $data[0], 126 'port' => $data[1] 127 ); 128 } 129 130 /** 131 * This command will reset all the masters with matching name. 132 * The pattern argument is a glob-style pattern. 133 * The reset process clears any previous state in a master 134 * (including a failover in progress), and removes every slave 135 * and sentinel already discovered and associated with the master. 136 * 137 * @param string $pattern 138 * @return int 139 */ 140 public function reset($pattern) 141 { 142 return $this->redis->rawCommand('SENTINEL', 'reset', $pattern); 143 } 144 145 /** 146 * Force a failover as if the master was not reachable, 147 * and without asking for agreement to other Sentinels 148 * (however a new version of the configuration will be published 149 * so that the other Sentinels will update their configurations). 150 * 151 * @param string $master_name 152 * @return boolean 153 */ 154 public function failOver($master_name) 155 { 156 return $this->redis->rawCommand('SENTINEL', 'failover', $master_name) === 'OK'; 157 } 158 159 /** 160 * @param string $master_name 161 * @return boolean 162 */ 163 public function ckquorum($master_name) 164 { 165 return $this->checkQuorum($master_name); 166 } 167 168 /** 169 * Check if the current Sentinel configuration is able to 170 * reach the quorum needed to failover a master, and the majority 171 * needed to authorize the failover. This command should be 172 * used in monitoring systems to check if a Sentinel deployment is ok. 173 * 174 * @param string $master_name 175 * @return boolean 176 */ 177 public function checkQuorum($master_name) 178 { 179 return $this->redis->rawCommand('SENTINEL', 'ckquorum', $master_name); 180 } 181 182 /** 183 * Force Sentinel to rewrite its configuration on disk, 184 * including the current Sentinel state. Normally Sentinel rewrites 185 * the configuration every time something changes in its state 186 * (in the context of the subset of the state which is persisted on disk across restart). 187 * However sometimes it is possible that the configuration file is lost because of 188 * operation errors, disk failures, package upgrade scripts or configuration managers. 189 * In those cases a way to to force Sentinel to rewrite the configuration file is handy. 190 * This command works even if the previous configuration file is completely missing. 191 * 192 * @return boolean 193 */ 194 public function flushConfig() 195 { 196 return $this->redis->rawCommand('SENTINEL', 'flushconfig'); 197 } 198 199 /** 200 * This command tells the Sentinel to start monitoring a new master with the specified name, 201 * ip, port, and quorum. It is identical to the sentinel monitor configuration directive 202 * in sentinel.conf configuration file, with the difference that you can't use an hostname in as ip, 203 * but you need to provide an IPv4 or IPv6 address. 204 * 205 * @param $master_name 206 * @param $ip 207 * @param $port 208 * @param $quorum 209 * @return boolean 210 */ 211 public function monitor($master_name, $ip, $port, $quorum) 212 { 213 return $this->redis->rawCommand('SENTINEL', 'monitor', $master_name, $ip, $port, $quorum); 214 } 215 216 /** 217 * is used in order to remove the specified master: the master will no longer be monitored, 218 * and will totally be removed from the internal state of the Sentinel, 219 * so it will no longer listed by SENTINEL masters and so forth. 220 * 221 * @param $master_name 222 * @return boolean 223 */ 224 public function remove($master_name) 225 { 226 return $this->redis->rawCommand('SENTINEL', 'remove', $master_name); 227 } 228 229 /** 230 * The SET command is very similar to the CONFIG SET command of Redis, 231 * and is used in order to change configuration parameters of a specific master. 232 * Multiple option / value pairs can be specified (or none at all). 233 * All the configuration parameters that can be configured via sentinel.conf 234 * are also configurable using the SET command. 235 * 236 * @param $master_name 237 * @param $option 238 * @param $value 239 * @return boolean 240 */ 241 public function set($master_name, $option, $value) 242 { 243 return $this->redis->rawCommand('SENTINEL', 'set', $master_name, $option, $value); 244 } 245 246 /** 247 * get last error 248 * 249 * @return string 250 */ 251 public function getLastError() 252 { 253 return $this->redis->getLastError(); 254 } 255 256 /** 257 * clear last error 258 * 259 * @return boolean 260 */ 261 public function clearLastError() 262 { 263 return $this->redis->clearLastError(); 264 } 265 266 /** 267 * sentinel server info 268 * 269 * @return string 270 */ 271 public function info() 272 { 273 return $this->redis->info(); 274 } 275 276}

本文转自 https://www.100txy.com/article/261,如有侵权,请联系删除。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

KVM调整cpu和内存

一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid

Nginx + lua +[memcached,redis]

精品案例1、Nginxluamemcached,redis实现网站灰度发布2、分库分表/基于Leaf组件实现的全球唯一ID(非UUID)3、Redis独立数据监控,实现订单超时操作/MQ死信操作SelectPollEpollReactor模型4、分布式任务调试Quartz应用

Redis主从模式的常用类型

本文介绍Redis主从模式的常用类型。Redis的可靠性主要有主从模式和集群模式。对于主从模式而言,Redis有以下方案:Sentinel方案;Keepalived方案。Sentinel方案作为Redis主推的官方方案,主要的实现原理是通过引入哨兵sentinel节点,来投标决定master节点故障后,