所以我将 Redis 添加到一个已经开发的项目中,我想知道将这些缓存调用放在哪里。有现有的模型,我想知道是否可以将 redis 注入模型,然后用缓存代码包装每个查询,如下所示:
$cacheKey = "table/{$id}";
// If table entity is not in cache
if (!$predis->exists($cacheKey)) {
// Pre-existing database code
$this->db->query('SELECT * FROM table WHERE table.id = "'.$id.'" ');
$query = $this->db->get();
$result = $query->result_array();
// Set entity in redis cache
$predis->set($cacheKey, json_encode($result[0]));
return $result[0];
}
// Return cached entity from redis
return json_decode($predis->get($cacheKey), true);
但我只是想知道这是否是一个肮脏的黑客,或者实际上是最好的做事方式,它是放置缓存代码的最合适的地方吗?我从以前的项目中了解到,最好是第一次以正确的方式做事!