TP6 redis鍵過期命令實現 事件通知


安裝redis

Windows下載地址 https://github.com/tporadowski/redis/releases
根據系統情況下載安裝

cmd 窗口  redis-server.exe redis.windows.conf

Linux源碼安裝
下載地址:http://redis.io/download,下載最新穩定版本。

# wget http://download.redis.io/releases/redis-6.0.8.tar.gz
# tar xzf redis-6.0.8.tar.gz
# cd redis-6.0.8
# make

# cd src
# ./redis-server

配置TP6

config/cache.php

// redis緩存
'redis'   =>  [
    // 驅動方式
    'type'   => 'redis',
    // 服務器地址
    'host'       => '127.0.0.1'
],

啟動redis 更改配置

redis-cli.exe

輸入 config get *
查看 

113) "notify-keyspace-events"
114) ""

如果是空 執行

config set notify-keyspace-events Ex

config get *
查看

或者 編輯修改 redis.windows.conf

修改 notify-keyspace-events Ex

通過配置啟動 redis-server redis.windows.conf

配置 think 命令

自定義命令
php think make:command Hello hello

會生成一個app\command\Hello

配置config/console.php文件

<?php
return [
    'commands' => [
        'hello' => 'app\command\Hello',
    ]
];

運行 php think 
有沒有hello 命令

hello.php 編寫業務邏輯

<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

// use app\common\controller\MyRedis;
use think\facade\Cache;

class Hello extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('hello')
            ->setDescription('the hello command');
    }

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

        $this->getkey();
        $output->writeln("ok");

    }

    public function getkey(){
        // ini_set('default_socket_timeout', -1);
        //redis 訂閱 第二個 是個 回調函數
        Cache::store('redis')->handler()->psubscribe(array('__keyevent@0__:expired'), 'app\command\Hello::keyCallback');//回調必須寫絕對路徑 要不然 會報錯


    }
     public static function keyCallback($redis, $pattern, $channel, $message) {
        file_put_contents('order.log',$message."\r\n",FILE_APPEND);
        //隨便寫個 log 記錄 不要復制  要不然會在項目的 根目錄出現  記得寫路徑
        //在這里寫邏輯啊 寫數據庫操作 
        
        echo '已刪除訂單編號:'.$message;
    }
}

編寫你的測試代碼

app/index/index
   use think\facade\Cache;
   Cache::store('redis')->setex("wuya1","10","123");

測試

在終端執行 php think hello
頁面運行你的測試代碼 ***\index\index

終端會打印出
已刪除訂單編號:**


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM