thinkphp5 配置redis的订阅和发布模式

1. redis 配置

修改config配置文件,使用thinkphp的cache中的redis命令,为了不影响默认的cache配置,所以我们可以把类型配置成混合模式

'cache'=> [
        // 驱动方式,type为complex时为混合类型
        'type'   => 'complex',
        'default'=>[
            // 驱动方式
            'type'   => 'File',
            // 缓存保存目录
            'path'   => CACHE_PATH,
            // 缓存前缀
            'prefix' => '',
            // 缓存有效期 0表示永久缓存
            'expire' => 0,
        ],
        // redis缓存
        'redis'   =>  [
            // 驱动方式
            'type'   => 'redis',
            'port'   => '6379',
            // 服务器地址
            'host' => '127.0.0.1',
            'password'   => '',
            // 缓存有效期 0表示永久缓存
            'expire' => 0,
        ],
    ],

2.订阅命令

定义一个command命令文件

application/admin/command/RedisSub.php

namespace app\admin\command;

use think\Cache;
use think\console\Command;
use think\console\Input;
use think\console\Output;


class RedisSub extends Command
{
    //命令描述
    protected function configure()
    {
        $this->setName('redisSub')->setDescription('redisSub');
    }

    protected function execute(Input $input, Output $output)
    {

        $redis = Cache::store('redis')->handler();
        $redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);

        //订阅这个频道,获取频道消息
        /*$res = $redis->subscribe(['qlp:index'],function($instance,$channel,$message){//实例,频道,消息
        });
        */

        //匹配适应规则的所有的频道消息
        $res = $redis->psubscribe(['qlp:*'],function($instance,$rule,$channel,$message){//实例,规则,频道,消息
            var_dump($channel.'-'.$message);
            //业务逻辑:发送短信,推送给用户等等
        });

        $output->writeln( date('Y-m-d H:i:s'));//输出内容
    }
}

注意: $redis->setOption(\Redis::OPT_READ_TIMEOUT, -1); 这句代码的作用是防止redis连接超时而退出,本地测试不加会报错

[RedisException]
  read error on connection

把命令文件配置到命令中

application/command.php

<?php
return [
    'app\admin\command\Crud',
    'app\admin\command\Menu',
    'app\admin\command\Install',
    'app\admin\command\Min',
    'app\admin\command\Addon',
    'app\admin\command\Api',
    'app\admin\command\RedisSub' //新增一条命令
];

这样再执行php think命令的时候就能看到一条新的RedisSub命令

C:\homestead\code\qilipu>D:\phpstudy_pro\Extensions\php\php5.6.9nts\php.exe  think
Think Console version 0.1

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -V, --version         Display this console version
  -q, --quiet           Do not output any message
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  addon              Addon manager
  api                Build Api document from controller
  build              Build Application Dirs
  clear              Clear runtime file
  crud               Build CRUD controller and model from table
  help               Displays help for a command
  install            New installation of FastAdmin
  list               Lists commands
  menu               Build auth menu from controller
  min                Compress js and css file
  redisSub           redisSub  //这条就是新加的

然后执行redis订阅的命令

C:\homestead\code\qilipu>D:\phpstudy_pro\Extensions\php\php5.6.9nts\php.exe  think  redisSub

3.发布命令

定义一个控制器,通过网址进行发布消息

<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Cache;
class MyRedis extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function pub()
    {
        $redis = Cache::store('redis')->handler();
        $res = $redis->publish('qlp:index','test 666');
        var_dump('发布订阅消息成功,接受者数量为:'.$res);
        //关闭
        $redis->close();
    }
}

也可以使用命令的方式推送

127.0.0.1:6379[1]> publish qlpᄀ:* hellowrold
(integer) 1
127.0.0.1:6379[1]> publish qlp:* hellowrold
(integer) 2

消息发布成功后我们会看到订阅者能收到消息

C:\homestead\code\qilipu>D:\phpstudy_pro\Extensions\php\php5.6.9nts\php.exe  think  redisSub
C:\homestead\code\qilipu\application\admin\command\RedisSub.php:40:
string(18) "qlp:index-test 666"
C:\homestead\code\qilipu\application\admin\command\RedisSub.php:40:
string(18) "qlp:index-test 666"
C:\homestead\code\qilipu\application\admin\command\RedisSub.php:40:
string(18) "qlp:index-test 666"
C:\homestead\code\qilipu\application\admin\command\RedisSub.php:40:
string(18) "qlp:index-test 666"

注意的是为了避免php命令的无故退出,保证系统的可用性可以是使用supervisor守护进程的方式,保证订阅者不退出。

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oraclechaozi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值