Winlams 2025-03-01 21:50 采纳率: 54.5%
浏览 5

thinkphp6 Command 监听redis过期的问题

thinkphp6 Command 监听redis过期的问题

protected function execute(Input $input, Output $output)
    {
        $redis = Cache::store('crx_upfile')->handler();
        //设置redis超时时间 -1永不超时
        $redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
        //订阅redis * 库的过期事件,触发app\command\RedisZeroCallback::keycallback命令
        $redis->psubscribe(array('__keyevent@0__:expired'), 'app\command\RedisZeroCallback::keycallback');

        //$output->writeln('回调完了');
    }
    public static function keycallback($redisp, $pattern, $chan, $msg){
        echo 1111;
        $redisp->set("er","232");
        var_dump($redisp->get("er"));
}

为什么$redisp->set没反应?keycallback里就算重新$redis = Cache::store('crx_upfile')->handler();也没反应

  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2025-03-01 21:50
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    解答

    ThinkPHP6 提供了一个 Redis 服务,可以用来监听 Redis 中的 key 过期事件。下面是一个简单的示例代码:

    use think\console\Command;
    use think\console\Input;
    use think\console\Output;
    use think\redis\Redis;
    
    class RedisExpireCommand extends Command
    {
        protected function configure()
        {
            // 指定命令名称和描述
            $this->setName('redis:expire')
                 ->setDescription('监听 Redis 中的 key 过期事件');
        }
    
        protected function execute(Input $input, Output $output)
        {
            // 创建 Redis 客户端
            $redis = new Redis();
            $redis->connect('localhost', 6379);
    
            // 监听 Redis 中的 key 过期事件
            $redis->pSubscribe(['__keyevent@0__:expired'], function ($message) use ($output) {
                // 处理过期事件
                $output->writeln("Key [{$message[1]}] has expired.");
            });
        }
    }
    

    在上面的代码中,我们创建了一个 Redis 客户端,然后使用 pSubscribe 方法监听 Redis 中的 __keyevent@0__:expired 事件,这个事件会在 Redis 中的 key 过期时触发。最后,我们使用 Output 对象将过期事件的信息输出到控制台。

    需要注意的是,在使用 pSubscribe 方法时,需要确保 Redis 客户端已经连接成功,并且需要在 Redis 中开启了 pub/sub 模式。

    评论

报告相同问题?

问题事件

  • 创建了问题 3月1日