发布订阅讲解
Redis 发布订阅 (pub/sub) 是一种消息通信模式:发送者 (pub) 发送消息,订阅者 (sub) 接收消息。Redis 客户端可以订阅任意数量的频道。
客户端可以订阅一个或者多个频道,从而成为这些频道的订阅者,每当有其他客户端向被订阅的频道发送消息时,频道的订阅者都会收到这条消息。
例如:
客户端一订阅 runoobchat 频道
127.0.0.1:6379> subscribe runoobchat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "runoobchat"
3) (integer) 1
客户端二向频道 runoobchat 发送消息
127.0.0.1:6379> publish runoobchat "Redis publish test"
(integer) 1
127.0.0.1:6379>
客户端一就接收到客户端二发送过来的消息
127.0.0.1:6379> subscribe runoobchat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "runoobchat"
3) (integer) 1
1) "message"
2) "runoobchat" # 订阅频道
3) "Redis publish test" # 频道二发送的消息
PHP代码实现
发布订阅-广播消息推送
index.php
<?php
$redis = new Redis();
$redis->connect("127.0.0.1",6379);
$redis->auth("root");
//循环始终在运行,因为需要不断接收来自频道的消息
while (true){
echo time();
ini_set('default_socket_timeout', -1); //不超时
$result = $redis->subscribe(["new.it"],"callback");# 接收来自发送者发送的消息,callback:为回调地址
print_r($result);
sleep(0.1);
}
function callback($instance,$channelName,$message)
{
print_r("\n".$message);//输出发送的消息
}
?>
在 linux 中运行 index.php 文件,然后访问publish.php文件发送消息
[root@localhost ~]# php index.php
1631525402
Hello 小洪帽i
publish.php
<?php
$redis = new Redis();
$redis->connect("127.0.0.1",6379);
$redis->auth("root");
$message = "Hello 小洪帽i";
$redis->publish("new.it",$message);//向new.it发送一条消息
echo "消息发送成功";
?>