thinkphp6用redis的发布与订阅功能

482 阅读2分钟

今天说下在thinkphp 6下使用redis的发布与订阅功能。废话少说,直接开始。 先说下我的环境情况,使用的宝塔。

1. 安装redis,在宝塔的面板的软件商店里找到redis。这里我的已经安装好了。我按装的版本是6.2.6。不是最新的版本。

image.png

2. 设置redis的密码,我认为这个是很有必要的。 image.png

3. thinkphp6框架的安装这里就不说了,设置redis的配置文件。打开框架目录下config/cache.php

image.png

        'redis'   =>  [

            // 驱动方式

            'type' => 'redis',

            // 服务器地址

            'host'     => '127.0.0.1',

            // redis密码:如果没有设置就为空

            'password' => '123',

            // 服务器端口

            'port'     => '6379',

        ],

4. 进入到项目目录   image.png

5. 运行命令生成一个自定义命令类文件

php think make:command Hello hello

6. 打开app\command\Hello.php文件

(1)引入Cache,Redis,Db

use think\facade\Cache;

use Redis;

use think\facade\Db;   image.png

(2)指令配置

 protected function configure()

    {

        // 指令配置

        $this->setName('hello')

            ->setDescription('the hello command');

    }

(3)在execute做逻辑的处理

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

  {
 
    // 指令输出
     
    $redis = Cache::store('redis');

    $redis = Cache::store('redis')->handler();

    $redis->setOption(Redis::OPT_READ_TIMEOUT, -1); // 设置连接超时时间为 10 秒

    $redis->subscribe(['my_channel'], function($redis, $channel, $data) {

     $da=json_decode($data,true);

      // 插入数据到MySQL中

       try {

              $qu = Db::connect('mysql') -> table('div_article_content7') -> insertAll($da);

        } catch (\Exception $e) {

        // 处理异常

       echo 'Error: ' . $e->getMessage();

      }
  });
}

7. 配置config/console.php文件

`<?php

// +----------------------------------------------------------------------

// | 控制台配置

// +----------------------------------------------------------------------

return [

    // 指令定义

    'commands' => [

        'hello' => 'app\command\Hello',

    ],

];`

  8.在app\controller\Index.php控制器里添加publish方法

  `public function publish(){

    $redis = Cache::store('redis');
    $query = Db::connect('www_netbolg_cn') -> table('div_article_content7')->select()->toArray();
    $data=json_encode($query); 
    $res=$redis->publish('my_channel', $data);

}`

注意,控制器要引入

`use think\facade\Db;

use think\facade\Cache;`

image.png

9.进入到项目目录 cd /www/wwwroot/tp.netbolg.cn image.png

10. 测试下 php think  结果显示有hello这个命令了。 image.png

11. 运行hello 命令 image.png

12. 访问Index.php控制器的publish方法

image.png

13. 到数据库里,查看有没有数据插入。

image.png

结果是有数据插入,证明发布和订阅这个功能是没问题了的。但这里有个问题,如果关掉运行命令窗口,那就不行了,其实可以这样解决的。

nohup php think hello > mylog.log &

这样就可以在后台运行该命令了。

最后,可能写的过程中还有很多不好的地方,希望大家能指出来,在此,谢谢大家