Query result served from cache – 永夜 https://www.shuijingwanwq.com 没有不值得去解决的问题,也没有不值得去学习的技术! Sun, 17 May 2026 06:30:10 +0000 zh-Hans hourly 1 https://wordpress.org/?v=7.0 在 Yii2 中,查询缓存未生效的排查分析 https://www.shuijingwanwq.com/2025/07/07/9198/ https://www.shuijingwanwq.com/2025/07/07/9198/#respond Mon, 07 Jul 2025 01:58:44 +0000 https://www.shuijingwanwq.com/?p=9198 浏览量: 120 1、代码实现如下


    /**
     * 获取热门标签
     *
     * @param int $limit 获取数量,默认10个
     * @return UseCaseTag[]
     * @throws \Throwable
     */
    public static function getHotTags(int $limit = 30): array
    {
        Yii::info(
            [
                '获取热门标签',
                self::getDb()->enableQueryCache
            ]
        );
        return self::getDb()->cache(function ($db) use ($limit) {
            return self::find()
                ->where(['status' => self::STATUS_NORMAL])
                ->orderBy(['case_count' => SORT_DESC])
                ->limit($limit)
                ->all();
        }, 300); // 缓存 300 秒
    }


2、已经确认 self::getDb()->enableQueryCache 的值为 true,但是每一次执行到此方法,仍然会执行对应的 SQL,如图1
已经确认 self::getDb()->enableQueryCache 的值为 true,但是每一次执行到此方法,仍然会执行对应的 SQL

图1



SELECT * FROM `use_case_tags` WHERE `status`=1 ORDER BY `case_count` DESC LIMIT 30


3、在 Debug Bar 中,有 3 条日志。决定分析一下,是否表明缓存已经生效,只不过日志中仍然会有 SQL 语句罢了


yii\db\Command::query	SELECT * FROM use_case_tags WHERE status=1 ORDER BY case_count DESC LIMIT 30

yii\redis\Connection::executeCommand	Executing Redis Command: GET

yii\db\Command::query	Query result served from cache


4、在 Yii2 的 Debug Bar 中,即使 查询缓存已命中并返回缓存结果,仍然可能看到类似这样的日志条目。这是因为:Yii2 在执行 ->cache() 时,为了判断是否已经存在缓存,会构建并准备 SQL 命令对象。然后才检查。决定清除掉 Redis 中的所有 key,然后再次查看 Debug Bar,确定第 1 次是写入缓存,第 2 次是读取缓存,缓存是起效的。如图2、图3
在 Yii2 的 Debug Bar 中,即使 查询缓存已命中并返回缓存结果,仍然可能看到类似这样的日志条目

图2

决定清除掉 Redis 中的所有 key,然后再次查看 Debug Bar,确定第 1 次是写入缓存,第 2 次是读取缓存,缓存是起效的

图3



Saved query result in cache

Query result served from cache


]]>
https://www.shuijingwanwq.com/2025/07/07/9198/feed/ 0