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

Laravel中Redis PUT缓存方法报错:PUT不是Redis注册命令

解决Laravel中Redis缓存最新文章时的PUT命令错误

这个问题的核心是你混淆了Laravel Cache门面和Redis门面的方法差异:

错误原因

Redis门面直接对接原生Redis客户端,只能使用Redis官方支持的命令(比如GET、SET、SETEX等),而PUT并不是Redis原生命令——put是Laravel Cache门面提供的封装方法,专门用来简化缓存操作的。你直接调用Redis::put(),自然会触发Predis\ClientException错误。

解决方案1:使用Laravel Cache门面(推荐)

Cache门面已经帮你封装了缓存的序列化、驱动适配、过期时间处理等逻辑,代码更简洁也更符合Laravel的开发规范:

public function latest($count) {
    $key = 'latest.' . $count;
    $cacheKey = $this->getCacheKey($key);

    // remember方法自动处理缓存命中/未命中逻辑
    return Cache::remember($cacheKey, 1, function () use ($count) {
        return Articles::orderBy('id', 'desc')->take($count)->get();
    });
}

这里的1代表缓存过期时间(单位:分钟),如果需要秒级过期,可以用now()->addSeconds(1)替代数字1。

解决方案2:坚持使用Redis门面(原生Redis命令)

如果一定要直接操作Redis,需要使用Redis原生的SETEX命令(设置值同时指定过期时间),并且手动处理对象的序列化/反序列化(因为Redis只能存储字符串):

public function latest($count) {
    $key = 'latest.' . $count;
    $cacheKey = $this->getCacheKey($key);

    $articles_latest = Redis::get($cacheKey);
    if ($articles_latest) {
        // 反序列化Redis中存储的字符串
        return unserialize($articles_latest);
    }

    $articles_latest = Articles::orderBy('id', 'desc')->take($count)->get();
    // 使用SETEX命令:key、过期时间(秒)、序列化后的内容
    Redis::setex($cacheKey, 60 * 1, serialize($articles_latest));
    return $articles_latest;
}

注意:这里把过期时间改成了60 * 1(秒),因为Redis的SETEX命令过期时间单位是秒,而原来你写的1如果是分钟的话,要对应转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:28:13