+
95
-

回答

还有一种sub pub消息

消息生产端

<?php

$channelName = "testPubSub";
$channelName2 = "testPubSub2";
//向指定频道发送消息
try {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
for ($i = 0; $i < 5; $i++) {
$data = array('key' => 'key'.$i, 'data' => 'testdata');
$ret = $redis->publish($channelName, json_encode($data));
print_r($ret);
}

} catch (Exception $e) {
echo $e->getMessage();
}

消息订阅端,可一次订阅不同的通道消息

<?php

//声明测试频道名称
$channelName = "testPubSub";
$channelName2 = "testPubSub2";
$redis = new Redis();
//建立一个长链接
$redis->connect('127.0.0.1', 6379);
try {

$redis->subscribe(array($channelName, $channelName2), function ($redis, $chan, $msg) {
echo "channel:".$chan.",message:".$msg."\n";
});
} catch (Exception $e) {
echo $e->getMessage()."\n";
}


网友回复

我知道答案,我要回答