TP6 redis psubscribe订阅 实现缓存过期后执行业务逻辑

一、psubscribe

redis订阅命令
Cache::store(‘redis’)->handler()->psubscribe(array(‘keyevent@1:expired’), ‘app\command\RedisCallback::keycallback’);
订阅redis 1 库的过期事件,触发app\command\RedisCallback::keycallback命令

二、使用步骤

1.开启reids过期事件通知

在redis配置文件中搜索‘notify-keyspace-events’(1062行左右)
notify-keyspace-events “Ex”
在这里插入图片描述

2.创建自定义指令

php think make:command RedisCallback callback

<?php
declare (strict_types = 1);

namespace app\command;

use app\server\Redis;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;

class RedisCallback extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('callback')->setDescription('redis过期回调');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('进命令了');
        //设置redis超时时间 -1永不超时
        Cache::store('redis')->handler()->setOption(\Redis::OPT_READ_TIMEOUT, -1);
        //订阅redis 1 库的过期事件,触发app\command\RedisCallback::keycallback命令
        Cache::store('redis')->handler()->psubscribe(array('__keyevent@1__:expired'), 'app\command\RedisCallback::keycallback');
        
        $output->writeln('回调完了');
    }
    public static function keycallback($redis, $pattern, $channel, $msg){
        echo "已删除订单编号" .$msg."\n\n";
        /*TODO处理业务逻辑*/
    }
}

2.运行自定义指令

nohup php think callback &
// 不挂断 , 后台运行 命令

3.查看结果

创建一个key(order:2015168)过期时间10秒
十秒后…

[root@wj lpf_admin]# 已删除订单编号order:2015168
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值