Redis 发布订阅 (pub/sub) 是一种消息通信模式

正文开始

https://blog.csdn.net/lihua123456123/article/details/113976202#:~:text=Redis%20%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85%20%28pub%2Fsub%29%20%E6%98%AF%E4%B8%80%E7%A7%8D%E6%B6%88%E6%81%AF%E9%80%9A%E4%BF%A1%E6%A8%A1%E5%BC%8F%EF%BC%9A%E5%8F%91%E9%80%81%E8%80%85%20%28pub%29%20%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF%EF%BC%8C%E8%AE%A2%E9%98%85%E8%80%85%20%28sub%29%20%E6%8E%A5%E6%94%B6%E6%B6%88%E6%81%AF%E3%80%82,%24redis-%3Econnect%28%27127.0.0.1%27%29%3B%20%24redis-%3Epsubscribe%28%5B%27redis%27%5D%2Cfunction%20%28%24redis%2C%20%24pattern%2C%20%24chan%2C%20%24msg%29%7B%20file_put_contents%28%27redis.log%27%2C%27%E6%88%91%E6%94%B6%E5%88%B0%E6%B6%88%E6%81%AF%EF%BC%9A%27.%24msg.PHP_EOL.%24chan%29%3B%20%7D%29%3B

Redis 发布订阅 (pub/sub) 是一种消息通信模式:发送者 (pub) 发送消息,订阅者 (sub) 接收消息。

首先打开终端命令行执行php文件,接收消息并且执行回调方法,文件代码如下:

$redis = new \Redis();
$redis-》connect('127.0.0.1');
$redis-》psubscribe(['channelName'],function ($redis, $pattern, $chan, $msg){
    print_r('我收到消息:'.$msg.PHP_EOL.$chan);
});

Thinkphp5框架下运行终端的代码:

<?php


define('APP_PATH', __DIR__ . '/application/');

define('BIND_MODULE','index/test/show');


// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';

index/test/show的代码

 public function show() {
        new RDS();
        RDS::psubscribe('channelName');
 }

另外用浏览器或者postman运行代码,发送消息给指定频道

$redis = new \Redis();
$redis-》connect('127.0.0.1');
$redis-》publish('channelName','hello world');

然后就可以在终端中看见发送的内容

正文结束

Could not connect to Redis at 127.0.0.1:6379: Connection refused 没有上一篇