redis的订阅功能就像微信公众号,你关注了就可以接收对应公众号的推送消息,你可以同时关注多个公众号,同样道理你可以关注多个订阅渠道channel,比如做一个redis订阅服务,在后台运行,推送过来的按渠道区分操作相关逻辑,比如邮件发送、异步处理问题、批量发送消息等。
新建一个sub.php作为订阅服务(修改后记得重启这个文件才生效):
<?php
set_time_limit(0);
$redis = new Redis();
if (!$redis->connect('127.0.0.1', 6379)) {
exit('redis连接失败');
}
//监听了两个渠道test_queue和test_error,回调
$redis->subscribe(['test_queue', 'test_error'], 'callback');
//the redis instance, the channel name, and the message
function callback($redis, $channel_name, $message)
{
//可以取消订阅某个渠道
#$redis->unsubscribe(['test_error']);
//测试是否启动了订阅服务
if ($message=='ping') return;
//在终端输出
echo 'channel_name:' . $channel_name . ';message:' . PHP_EOL . $message . PHP_EOL;
//记录日志
file_put_contents('subscribe_'.$channel_name . ".log", $message . PHP_EOL . '==============================' . PHP_EOL, FILE_APPEND);
}然后命令启动(实际上这个文件最好设置后台运行并且监听异常):
php sub.php
新建一个发布消息的客户端push.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
//发送消息客户端
$redis = new Redis();
if (!$redis->connect('127.0.0.1', 6379)) {
exit('redis连接失败');
}
//测试一下是否有订阅
if (!$redis->publish('test_queue', 'ping')) {
exit('订阅服务未启动');
}
for ($i = 0; $i <= 6; $i++) {
//模拟一个消息
$message = ['msg' => 'success', 'code' => 0, 'data' => ['num' => $i, 'type' => 'normal', 'time' => date('Y-m-d H:i:s')]];
if ($i % 3 == 0) {
//随便写点不一样的
$message['data']['type'] = 'error';
//新的渠道
$redis->publish('test_error', json_encode($message));
} else {
$redis->publish('test_queue', json_encode($message));
}
//延迟0.5秒
usleep(500000);
}在浏览器访问push.php或者命令行php push.php
sub.php终端输出:

同时生成了日志文件

日志内容如下:
{"msg":"success","code":0,"data":{"num":1,"type":"normal","time":"2022-11-08 10:00:18"}}
==============================
{"msg":"success","code":0,"data":{"num":2,"type":"normal","time":"2022-11-08 10:00:18"}}
==============================
{"msg":"success","code":0,"data":{"num":4,"type":"normal","time":"2022-11-08 10:00:19"}}
==============================
{"msg":"success","code":0,"data":{"num":5,"type":"normal","time":"2022-11-08 10:00:20"}}
===========error文件==============
{"msg":"success","code":0,"data":{"num":0,"type":"error","time":"2022-11-08 10:00:17"}}
==============================
{"msg":"success","code":0,"data":{"num":3,"type":"error","time":"2022-11-08 10:00:19"}}
==============================
{"msg":"success","code":0,"data":{"num":6,"type":"error","time":"2022-11-08 10:00:21"}}
==============================按这种方式可以做很多东西功能了。