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

Laravel中Cache::remember与Cache::put无法写入Redis的问题

Laravel Cache::remember/put 无法写入Redis,但Redis facade直接调用正常

我正在测试Redis写入方法(Item数据需频繁读取、极少写入),发现\Cache::remember和Cache::put完全无法工作,但直接使用Redis facade的set方法却能正常写入Redis并设置TTL。

测试代码(位于App\Jobs\ItemsCachingJob)

<?php

namespace App\Jobs;

use App\Library\Services\Interfaces\LogInterface;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Item;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

/*
php artisan job:dispatchNow ItemsCachingJob
*/

class ItemsCachingJob
{
    // Interface for logging messages
    protected $logger;
    use Dispatchable;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->logger = app(LogInterface::class);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // ... 省略其他代码
        $ret = \Cache::remember($redisUniqueKey.'aaa', $itemsCachingHours, function() use($item) {
            return serialize( $item->toArray());
        });
        \Log::info($ret); // 日志中能看到序列化后的字符串,但Redis中无对应数据

        $ret2 = Cache::put($redisUniqueKey.'bbb', serialize( $item->toArray()), $itemsCachingHours);
        \Log::info($ret2);  // 日志中显示布尔值"1",但Redis中无对应数据

        $ret3 = Redis::set($redisUniqueKey, serialize( $item->toArray()));
        \Log::info($ret3); // Redis中能看到有效数据和键,日志显示OK状态
        Redis::expire($redisUniqueKey, $itemsCachingHours);
    }
}

疑问与版本信息

  • 我导入了use Illuminate\Support\Facades\Cache;,这个导入是否正确?
  • 使用的依赖版本:
"laravel/framework": "^9.47", 
"predis/predis": "^2.1",

可能的原因及解决方案

  1. 缓存驱动配置错误

    • 检查.env文件中的CACHE_DRIVER是否设置为redis,若配置为file、array等其他驱动,Cache facade会写入对应存储而非Redis。同时确认REDIS_HOST、REDIS_PORT等Redis连接配置是否正确。
  2. 缓存前缀差异

    • Laravel的Cache facade会自动为键名添加config/cache.php中配置的prefix前缀,而Redis facade直接使用原始键名。可以通过Cache::getPrefix()查看当前前缀,再用带前缀的键名(如prefix:redisUniqueKeyaaa)去Redis中查询,确认数据是否实际已写入。
  3. TTL参数单位不匹配

    • Cache::remember和put的TTL参数默认接受分钟数,而Redis::expire接受秒数。如果$itemsCachingHours是小时数,Cache方法会将其解析为分钟(比如1小时被当成1分钟,很快过期),而Redis的expire转成秒数才正确。修正方式:将Cache方法的TTL转换为分钟,比如$itemsCachingHours * 60。
  4. Redis存储连接不一致

    • 若配置了多个Redis存储,确认config/cache.php中stores.redis.connection项指定的连接,是否与Redis facade默认使用的连接一致。
  5. 导入正确性

    • 你导入的use Illuminate\Support\Facades\Cache;是正确的,代码中无论是\Cache还是Cache的调用方式都有效。

内容的提问来源于stack exchange,提问作者Petro Gromovo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:51:36