Redis消息订阅

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();
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值