測試環境:windows 10 + phpStudy
配置redis配置文件 redis.windows.conf
notify-keyspace-events "Ex"
重啟redis服務
重新打開一個控制台窗口,執行命令
psubscribe __keyevent@0__:expired
打開新窗口執行了阻塞訂閱操作后的終端,等會會有信息輸出:
C:\Users\admin>redis-cli
127.0.0.1:6379> psubscribe __keyevent@0__:expired
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "__keyevent@0__:expired"
3) (integer) 1
再開啟一個終端,redis-cli 進入 redis,新增一個 6秒過期的鍵 username:
命令行完成了
二、借助TP5.1 的命令行工具
命令行工具的使用:https://www.kancloud.cn/manual/thinkphp5_1/354146
1、新建命令行pay
<?php
/**.-------------------------------------------------------------------------------------------------------------------
* | Github: https://github.com/Tinywan
* '------------------------------------------------------------------------------------------------------------------*/
namespace app\common\command;
use app\pay\service\RedisSubscribe;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
class Pay extends Command
{
// 配置指令
public function configure()
{
$this->setName('pay')
->addArgument('type', Argument::REQUIRED, "the type of the task that pay needs to run")
->setDescription('this is payment system command line tools');
}
// 執行指令
public function execute(Input $input, Output $output)
{
$type = $input->getArgument('type');
if ($type == 'psubscribe') {
// 發布訂閱任務
$this->psubscribe();
}
}
/**
* Redis 發布訂閱模式
*/
private function psubscribe()
{
$service = new RedisSubscribe();
$service->sub();
}
}
2、編寫腳本 RedisSubscribe.php
<?php
/**.-------------------------------------------------------------------------------------------------------------------
* | Github: https://github.com/Tinywan
* '------------------------------------------------------------------------------------------------------------------*/
namespace app\pay\service;
use redis\BaseRedis;
use think\facade\Log;
class RedisSubscribe
{
public function sub()
{
Log::error(get_current_date().'--過期事件的訂閱-- ');
$redis = BaseRedis::location(); //這里是直接連接本地redis
$redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
$redis->psubscribe(array('__keyevent@0__:expired'), function ($redis, $pattern, $chan, $msg) {
Log::error('[1]--過期事件的訂閱 ' . $msg);
});
}
}
說明:psubscribe( $patterns, $callback ) 方法的第二個參數為一個回調函數,這里我使用閉包作為一個回調。
官方解釋:匿名函數(Anonymous functions),也叫閉包函數(closures),允許 臨時創建一個沒有指定名稱的函數。最經常用作回調函數(callback)參數的值。當然,也有其它應用的情況。
3、在TP5 項目根目錄執行pay 命令工具
php think pay psubscribe
4、新打開console 窗口終端
C:\Users\admin>redis-cli
127.0.0.1:6379> setex UserName 10 Tinywan
OK
127.0.0.1:6379> get UserName
"Tinywan"
127.0.0.1:6379> get UserName
(nil)
127.0.0.1:6379>
5、查看打日志文件,看有沒有接收到過期的key
6、最終的結果如下所示
更高級的慢慢擴展
1、自動取消訂單
2、訂單完成后發送短信
3、延遲任務等等