Redis发布订阅简单测试
使用的是TP5.1框架
先安装redis的扩展
在tp5.1框架控制器中先链接Redis并发布一条内容信息
具体的Redis发布订阅命令请查看Redis手册
[简单写的代码]
第一步 :
<?php
namespace app\api\controller;
use think\Controller;
class Test extends Controller
{
public function getRedis(){
$redis = new \Redis();
$redis->connect('11.11.11.11',6379);
$redis->auth('111111');
//防止超时链接而断开,或者设置php的最大链接时间
$redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
$res = $redis->PUBLISH('first','获取数据');
dump($res);
}
public function getTwo(){
$redis = new \Redis();
$redis->connect('11.11.11.11',6379);
$redis->auth('111111');
//防止超时链接而断开,或者设置php的最大链接时间
$redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
$res = $redis->PUBLISH('firsts','获取数据123');
dump($res);
}
}
第二步 :
在与控制器同级目录新建command文件夹,并创建文件
使用tp5.1的command命令生成可执行的命令行
<?php
namespace app\api\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class PubSub extends Command
{
protected function configure()
{
$this->setName('getRedis') ->setDescription('发布订阅');
}
protected function execute(Input $input, Output $output)
{
$redis = new \Redis();
$redis->connect('11.11.11.11',6379);
$redis->auth('111111');
//防止超时链接而断开,或者设置php的最大链接时间
$redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
$redis->subscribe(["first"],function ($instance,$channel,$message){
dump($instance); //实例化的资源
dump($channel); //管道名称
dump($message); //发布的信息
});
// 或者
// $redis->psubscribe(["first:*"],function ($instance,$channelRule,$channel,$message){
// dump($message);
// });
}
}
第三步 :
在框架的app目录下的command.php新建命令,与第二步对应(PubSub)
<?php
return [
'app\api\command\PubSub',
];
第四步 :
在框架根目录 使用php think生成第二步配置的命令
并且执行 php think getRedis(自己设置的命令名称)
第五步 : 执行控制器中的命令,发布消息,,可以看到发布的消息内容
至此简单的发布订阅测试就算完成
但是发布订阅一般不会用于对消息内容要求高的逻辑中,一来太消耗内存,二来无法保证消息不会丢失,具体的优缺点可以具体搜索
想保证消息的准确性与确认消费,需要使用专业的消息中间件
以下是操作的截图,以上述步骤对应 :
第一步
第二步 :
第三步 :
第四步 :
第五步 :