?php/** * Redis Sentinel 完整实现 - 自动故障转移 */classRedisSentinelClient{private$sentinels;private$masterName;private$redis;private$timeout2;publicfunction__construct($sentinels,$masterNamemymaster){$this-sentinels$sentinels;// [[host 127.0.0.1, port 26379], ...]$this-masterName$masterName;$this-connect();}/** * 连接到当前主节点 */privatefunctionconnect(){$master$this-getMaster();if(!$master){thrownewException(无法获取主节点信息);}$this-redisnewRedis();$this-redis-connect($master[ip],$master[port],$this-timeout);}/** * 从 Sentinel 获取主节点信息 */privatefunctiongetMaster(){foreach($this-sentinelsas$sentinel){try{$snewRedisSentinel($sentinel[host],$sentinel[port],$this-timeout);$master$s-getMasterAddrByName($this-masterName);if($mastercount($master)2){return[ip$master[0],port$master[1]];}}catch(Exception$e){continue;// 尝试下一个 Sentinel}}returnnull;}/** * 执行 Redis 命令带自动重连 */publicfunctionexecute($method,$args[]){$maxRetries3;$attempt0;while($attempt$maxRetries){try{returncall_user_func_array([$this-redis,$method],$args);}catch(RedisException$e){$attempt;if($attempt$maxRetries){throw$e;}// 重新连接到新的主节点sleep(1);$this-connect();}}}/** * 魔术方法代理所有 Redis 方法 */publicfunction__call($method,$args){return$this-execute($method,$args);}/** * 获取集群状态 */publicfunctiongetClusterInfo(){foreach($this-sentinelsas$sentinel){try{$snewRedisSentinel($sentinel[host],$sentinel[port]);return[master$s-master($this-masterName),slaves$s-slaves($this-masterName),sentinels$s-sentinels($this-masterName)];}catch(Exception$e){continue;}}returnnull;}}// 使用示例 // 配置 Sentinel 节点$sentinels[[host127.0.0.1,port26379],[host127.0.0.1,port26380],[host127.0.0.1,port26381]];// 创建客户端$redisnewRedisSentinelClient($sentinels,mymaster);// 使用 Redis自动故障转移try{$redis-set(key,value);echo$redis-get(key).\n;// 获取集群信息$info$redis-getClusterInfo();print_r($info);}catch(Exception$e){echo错误: .$e-getMessage().\n;}sentinel.conf - 最短配置port 26379sentinel monitor mymaster 127.0.0.1 6379 2sentinel down-after-milliseconds mymaster 5000sentinel failover-timeout mymaster 10000