在 Yii2 中,查询缓存未生效的排查分析
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
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
Saved query result in cache Query result served from cache
近期评论