首页 » 网站推广 » php衔接sentinel技巧_用ThinkPHP6框架操作Redis Sentinel

php衔接sentinel技巧_用ThinkPHP6框架操作Redis Sentinel

访客 2024-12-05 0

扫一扫用手机浏览

文章目录 [+]

返回的信息

从图中可以看出Sentinel也是可以实行一些命令的查阅了Redis官网的一些信息之后,Shane创造通过Sentinel命令可以得到主从做事器的信息(端口号、地址等)

SENTINEL masters

php衔接sentinel技巧_用ThinkPHP6框架操作Redis Sentinel

返回的信息

php衔接sentinel技巧_用ThinkPHP6框架操作Redis Sentinel
(图片来自网络侵删)
既然能够得到主节点的信息(端口号、地址),那在程序实行写的操作之前,前辈行查询不就行了吗用TP6实行生命令(RawCommand)在TP6框架源码目录下/vendor/topthink/framework/src/think/cache/driver/在这个目录下有一个Redis类,是TP6供应的Redis扩展打开之后可以创造个中的扩展并不完全(没有RawCommand),须要进一步扩展

public function rawCommand($command, $arguments){return $this -> handler -> rawCommand($command, $arguments);}将代码写入保存然后在配置文件cache里写入一个新配置用来连接Sentinel

'sentinel' => ['host' => '127.0.0.1','port' => 26379,'type' => 'redis','timeout' => 0,'select' => 0]创建一个类,Shane取名SentinelWork

public function __construct(){$sentinelInfo = Cache::store('sentinel') -> rawCommand('SENTINEL', 'masters');halt($sentinelInfo);}写一个__construct方法并实行刚刚扩展好的rawCommand方法把稳:没扩展则实行不了这个方法

返回的信息

可以看到返回的信息和在终端实行看到的是千篇一律的接着做一个配置模板

/ passadmin为上上上篇条记约定的/private $master = ['host' => '127.0.0.1','port' => 6379,'password' => 'passadmin','select' => 0,'timeout' => 0];写完后在__construct方法中更换配置模板的host和port

public function __construct(){$sentinelInfo = Cache::store('sentinel') -> rawCommand('SENTINEL', 'masters');$this -> master['host'] = $sentinelInfo[0][3];$this -> master['port'] = $sentinelInfo[0][5];}写完后,再为自己创造的Redis扩展,扩展一个set方法

/ 这里先halt打印后续实行结果/public function set($key, $value){$redis = new Redis($this -> master);halt($redis -> set($key,$value));}扩展完后,来看一下整体代码

<?php/ @description: オラ!オラ!オラ!オラ! @author: Shane @time: 2020/4/19 19:04 /namespace app\cluster\controller;use app\BaseController;use think\App;use think\cache\driver\Redis;use think\facade\Cache;class SentinelWork extends BaseController{ private $master = [ 'host' => '127.0.0.1', 'port' => 6379, 'password' => 'passadmin', 'select' => 0, 'timeout' => 0 ]; public function __construct() { $sentinelInfo = Cache::store('sentinel') -> rawCommand('SENTINEL', 'masters'); $this -> master['host'] = $sentinelInfo[0][3]; $this -> master['port'] = $sentinelInfo[0][5]; } public function set($key, $value){ $redis = new Redis($this -> master); halt($redis -> set($key,$value)); }}注:这里可以不继续BaseController,直接将SentinelWork作为lib类库利用完成后,创建一个测试掌握器,引入SentinelWork调用个中的set方法(这里Shane输入redis:666这个键值对)

返复书息

返回true实行成功,再来终端进入cli查看下是否成功

实行情形

成功查询到数据,再去另一台云做事器看看

实行情形

同样成功查询到数据总结通过上述操作,当主理事器挂掉之后,Sentinel选举出新的主理事器之后不会导致原来的代码依旧去要求已经挂掉的做事器或是启动之后显示Read Only报错而是直接通过Sentinel返回的新的主理事器的信息(端口号和地址)来进行写的操作Shane在B站的TP6视频:BV1tJ411J7qZ
标签:

相关文章

招商蛇口中国房地产龙头企业,未来可期

招商蛇口(股票代码:001979),作为中国房地产企业的领军企业,自成立以来始终秉持“以人为本,追求卓越”的经营理念,致力于打造高...

网站推广 2025-02-18 阅读1 评论0