有没有办法获取密钥过期的剩余时间? 目前,我正在使用 Laravel 文件缓存驱动程序。
FileStore
继承了 Store
的代码。如果您想实现这个功能,您需要复制这个逻辑。具体请参考:https://github.com/laravel/framework/blob/5.1/src/Illuminate/Cache/FileStore.php#L50-L86。基于Josh的答案,我想出了一个宏:
在AppServiceProvider
的boot
方法中:
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