Redis 发布订阅
自定义命令行,创建一个频道
<?php
/**
* Created PhpStorm.
* User: 1971229701@qq.com
* Date: 2019/11/4
* Time: 16:08
*/
namespace app\home\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
class RedisPush extends Command
{
protected function configure()
{
$this->setName('redisPush')
->addOption('content','c',Option::VALUE_OPTIONAL,'连接地址','127.0.0.1')
->addOption('prop','p',Option::VALUE_OPTIONAL,'端口号','6379')
->addOption('password','ps',Option::VALUE_OPTIONAL,'密码','123456')
->setDescription('redis订阅推送');
}
protected function execute(Input $input, Output $output)
{
$content = $input->getOption('content');
$prop = $input->getOption('prop');
$password = $input->getOption('password');
$redis = new \Redis();
$redis->connect($content,$prop);
$redis->auth($password);
$redis->psubscribe(['channel'],function ($redis, $pattern, $channel, $message){
var_dump($redis, $pattern, $channel, $message);
});
}
}
服务端发布消息, publish(‘发布的频道’,'发布内容')
public function index()
{
$res = $this->redis->publish('channel', '消息订阅');
}
客户端接收消息 $redis->subscribe(array('chan-1', 'chan-2', 'chan-3'), 'f');
public function test()
{
// 设置超时时间,不然会链接超时
ini_set('default_socket_timeout', -1);
// set_time_limit(0);
try{
$redis = new \Redis();
$redis->pconnect('127.0.0.1', 6379,2);// 127.0.0.1 连接的IP,6379 连接的端口,2 连接的超时时长,单位:秒
$redis->auth('123456'); // 密码
//$redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
$channel = 'channel'; // channel
$redis->subscribe(array($channel), function ($redis, $channel, $message){
var_dump($message);
exit;
});
}catch (\Exception $e){
echo $e->getMessage();
}
}