PHP 实现Redis发布订阅消息及时通讯

2020-09-08 14:40:09 浏览数 (3)

订阅发布 也就是常说的生产者与消费者,常用于消息推送,就像你订阅了齐鲁晚报,然后每天送报人员将报纸给你送来一样,直接给代码。

目录

1.订阅

2.发布

1

订阅

代码语言:javascript复制
<?php
/**
* Created by PhpStorm.
* Author: Jason Ding
* Date: 2017/3/28
* Time: 10:05
*/

//订阅
ini_set('default_socket_timeout', -1); //不超时
$redis = new redis();
$result = $redis->connect('192.168.0.221', 6379);
$redis->auth('password');
$redis->select(15);
$redis->subscribe(array('齐鲁晚报'), 'callback');
function callback($instance,$channelName,$message){
echo $message;
}

2

发布

代码语言:javascript复制
<?php
/**
 * Created by PhpStorm.
 * Author: Jason Ding
 * Date: 2017/3/28
 * Time: 10:06
 */
//发布
$redis = new redis();
$result = $redis->connect('192.168.0.221', 6379);
$redis->auth('password');
$redis->select(15);
$message='happy new year';
$ret=$redis->publish('齐鲁晚报',$message);

var_dump($ret);

END

0 人点赞