1.新建Redis的publish的控制器
<?php
namespace app\api\controller;
use think\cache\driver\Redis;
class MyRedis
{
private $redis;
public function __construct()
{
//初始化Redis链接
$this->redis = new Redis();
}
public function RedisPublish()
{
//定义发布的信道名称
$channel = 'test_channel';
var_dump('开始发布数据');
for ($i=0; $i<50; $i++){
$data = "来自{$channel}频道的推送2--$i";
//发布数据
$this->redis->publish($channel, $data);
}
var_dump('发布数据结束');
//关闭
$this->redis->close();
}
}
2.使用php think make:command RedisSub命令自定义subscribe指令
a.在config/console.php文件中加入指令
b.执行php think命令查看指令是否生成
3.在subscribe中写入处逻辑
<?php
declare (strict_types = 1);
namespace app\command;
use think\cache\driver\Redis;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class RedisSub extends Command
{
protected function configure()
{
// 指令配置
$this->setName('redissub')
->setDescription('the redissub command');
}
protected function execute(Input $input, Output $output)
{
// 指令输出
$redis = new Redis();
//订阅的信道
$channel = 'test_channel';
echo "---- 订阅{$channel}这个频道,等待消息推送...---- <\n";
$redis->subscribe([$channel], function ($redis, $channel, $msg){
//消费订阅的消息的逻辑
var_dump($msg);
});
}
}
4.执行消费者命令
5.触发Publisher,发送消息给Subscriber
6.查看Subscriber的执行情况
至此结束。