本篇文章主要介紹Reids 鍵空間通知配合TP5 實作分散式縮時任務,希望對需要的朋友有幫助!
測試環境: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,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、延遲任務等等
相關推薦:《PHP7教學》
以上是PHP7之Reids鍵空間通知配合TP5 實作分散式延時任務的詳細內容。更多資訊請關注PHP中文網其他相關文章!