我使用的是tp5.1
安装redis 扩展不细节描述
phpstudy 安装的redis 需要修改默认配置文件
步骤1:
redis 的配置修改:
notify-keyspace-events "Ex"
重启redis
步骤2:
创建公用redis类
<?php namespace app\command\Controller; use think\cache\driver\Redis; class MyRedis { private $redis; public function __construct($host = '127.0.0.1', $port = 6379) { $this->redis = new Redis(); $this->redis->config('notify-keyspace-events','Ex');//开启redis key 过期通知(修改配置文件失效可加上) $this->redis->connect($host, $port); $this->redis->auth('123456'); } public function setex($key, $time, $val) { return $this->redis->setex($key, $time, $val); } public function set($key, $val) { return $this->redis->set($key, $val); } public function get($key) { return $this->redis->get($key); } public function expire($key = null, $time = 0) { return $this->redis->expire($key, $time); } public function psubscribe($patterns = array(), $callback) { $this->redis->psubscribe($patterns, $callback); } public function subscribe($patterns = array(), $callback) { $this->redis->subscribe($patterns, $callback); } public function setOption() { $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1); } }
步骤3:
//下单业务插入redis public function redis(){ $redis = new \app\command\Controller\MyRedis(); $order_num = 2; $redis->setex("orderNum_".$order_num,20,$order_num); echo "待确认订单生成成功,20 秒后自动取消订单号:".$order_num; } //取消订单、支付成功删除redis数据 public function noRedis(){ $redis = new \app\command\Controller\MyRedis(); $order_num = 2; //删除订单过期标记 $redis->del("orderNum_".$order_num); //修改数据库订单状态 Db::name('')->update(); echo "修改成功".$order_num; }
步骤4:
app->command.php
<?php return [ 'app\command\Test', ];
步骤5:
编辑监听方法 cmd运行 项目根目录 php think test
<?php namespace app\command; use think\console\Command; use think\console\Input; use think\console\Output; use app\common\controller\MyRedis; use think\Db; class Test extends Command { protected function configure() { // 指令配置 $this->setName('test') ->setDescription('测试订单过期处理'); // 设置参数 } protected function execute(Input $input, Output $output) { ini_set('default_socket_timeout', -1); // 指令输出 $redis = new \app\command\Controller\MyRedis(); //其他地方找的redis操作 $redis->setOption(); $redis->psubscribe(array('__keyevent@0__:expired'), function ($redis, $pattern, $chan, $msg) { echo PHP_EOL; echo "Pattern: $pattern\n"; echo "Channel: $chan\n"; echo "Payload: $msg\n\n"; echo 'order:订单处理成功\n'; /*业务逻辑处理*/ $quey = Db::name(); }); } }
前台下单后过期显示
处理成功