如何获取 Laravel(文件)缓存键的过期时间?

5

有没有办法获取密钥过期的剩余时间? 目前,我正在使用 Laravel 文件缓存驱动程序。

2个回答

6

3

基于Josh的答案,我想出了一个宏:

AppServiceProviderboot方法中:

Cache::macro('getTTL', function (string $key): ?int {
    $fs = new class extends FileStore {
        public function __construct()
        {
            parent::__construct(App::get('files'), config('cache.stores.file.path'));
        }

        public function getTTL(string $key): ?int
        {
            return $this->getPayload($key)['time'] ?? null;
        }
    };

    return $fs->getTTL($key);
});

使用方法:

Cache::getTTL('key_that_exists') // 20900 (in seconds)

Cache::getTTL('key_that_does_not_exist') // null

注意:此代码在 Laravel 10.0 中使用 PHP 8.1 进行测试。

Gist: https://gist.github.com/Script47/a0e189eb5b3a352517ae5185510f9e17


我尝试了你的宏,但在 Laravel 10.13.5 和 PHP 8.2.5 下出现了错误 "Call to undefined method Illuminate\Cache\FileStore::getTTL()"。 - Mike Scott

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接