You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用File缓存驱动时,缓存过期时间远短于设置的TTL

Laravel File缓存驱动TTL失效问题(缓存仅维持约1分钟)

问题描述

使用Laravel的File缓存驱动时,缓存文件可正常创建并访问,但设置的12小时TTL参数不生效,缓存仅维持约1分钟就被自动删除;切换为Database驱动时代码可正常运行,排除权限问题。

相关代码:

Route::get('setCache', function () {
    Cache::store('file')->put('testCache1', 'testCache1 value', now()->addHours(12));
});
Route::get('getCache', function () {
    dd(Cache::store('file')->get('testCache1'));
});

解决方案

1. 检查任务调度中的缓存清理频率

Laravel的cache:prune-stale命令用于清理过期缓存,如果被错误配置为每分钟执行,会误删未过期的缓存。打开app/Console/Kernel.php,检查调度任务:

// 错误示例:每分钟执行缓存清理
$schedule->command('cache:prune-stale')->everyMinute();

若存在上述配置,修改为合理频率,比如每日执行:

$schedule->command('cache:prune-stale')->daily();

2. 验证时间戳正确性

确保服务器系统时间与应用时间同步,now()->addHours(12)生成的过期时间是否符合预期。可在setCache路由中添加验证代码:

Route::get('setCache', function () {
    $expiresAt = now()->addHours(12);
    Cache::store('file')->put('testCache1', 'testCache1 value', $expiresAt);
    dd($expiresAt); // 检查输出时间是否为当前时间+12小时
});

若服务器时间偏差过大,会导致缓存提前失效,需同步服务器时间。

3. 检查File驱动配置

打开config/cache.php,确认file驱动的expire配置项是否被错误设置为1分钟:

'file' => [
    'driver' => 'file',
    'path' => storage_path('framework/cache/data'),
    // 若存在该行配置,会覆盖put方法设置的TTL,需删除
    // 'expire' => 60,
],

4. 查看缓存文件实际过期时间

进入storage/framework/cache/data目录,找到对应缓存文件,查看头部的expires时间戳:

a:2:{s:8:"expires";i:1718xxxxxxx;s:7:"content";s:17:"testCache1 value";}

将时间戳转换为可读时间,验证是否与预期的12小时后一致。若时间戳为1分钟后,说明now()->addHours(12)生成逻辑异常或配置被覆盖。

内容的提问来源于stack exchange,提问作者Mohammad Salehi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 00:54:54