php redis发布订阅的使用

1 篇文章 0 订阅

简介

Redis提供了基于“发布/订阅”模式的消息机制。此种模式下,消息发布者和订阅者不进行直接通信,发布者客户端向指定的频道(channel) 发布消息,订阅该频道的每个客户端都可以收到该消息。Redis提供了若干命令支持该功能,在实际应用开发时,能够为此类问题提供实现方法。

使用场景

  • 业务解耦
  • 异步处理

php使用

private function pub(){
        $this->redis->publish('chan-1','this is a message by chan1');
        $this->redis->publish('chan-2','this is a message by chan2111111111111111');
    }

    private function sub(){
        while(true){
            try {
                if(null === $this->redis){
                    $this->redis = (new Connect())->redis;
                    $this->output->writeln("Redis reconnection ");
                }

                $this->redis->subscribe(['chan-1', 'chan-2'], [$this,'task']);  // 第一个参数为订阅哪个频道,第二个参数为响应回调函数名称
            }catch (\Throwable $e){
                $this->output->writeln(date("Y-m-d H:i:s").",error:".$e->getMessage());
                $this->output->writeln("redis reconnected 10 seconds later");
                $this->redis = null;
                sleep(10);
            }
        }
    }

    public function task($instance, $channelName, $message){
        switch($channelName) {
            case 'chan-1':
                var_dump('chan-1'.$message);
                break;
            case 'chan-2':
                var_dump('chan-2'.$message);
                break;
        }
    }

效果

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值