1、用的是TP5框架,改写框架自带的redis类 thinkphp/library/think/cache/driver/Redis.php
//两台服务器都配置好了监控哨兵 //主从配置要设置好密码,两变密码最好一致,因为切换的时候要密码验证 protected $sentinel = array( array( 'host' => '116.62.111.1', // redis端口 'port' => 1940, // 密码 'password' => '123redis', 'select' => 0, 'timeout' => 1, 'expire' => 10000, 'persistent' => false, 'prefix' => 'subs', 'serialize' => true, ), array( 'host' => '116.62.111.2', // redis端口 'port' => 1940, // 密码 'password' => '123redis', 'select' => 0, 'timeout' => 1, 'expire' => 10000, 'persistent' => false, 'prefix' => 'subs', 'serialize' => true, ), );
2、初始化redis的链接配置,通过链接哨兵来获取当前的主从服务器的信息,保证每次都是读的主服务器
foreach ($this->sentinel as $sentinel){ try{ $this->handler->connect($sentinel['host'], $sentinel['port'], $this->options['timeout']); if ('' != $sentinel['password']) { $this->handler->auth($sentinel['password']); } break; }catch (\Exception $e){ continue; } }
3、测试只要一台服务器死,另外一台从几会自动切换成主机,把死的机子重启之后又会自动变成从机,自动同步关联。