0

所以我将 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);

但我只是想知道这是否是一个肮脏的黑客,或者实际上是最好的做事方式,它是放置缓存代码的最合适的地方吗?我从以前的项目中了解到,最好是第一次以正确的方式做事!

4

1 回答 1

0

您应该首先分析您的应用程序并找出最常调用的部分和最慢的部分。

如果您缓存整个 HTML 部分,而不是单个数据库行,您将获得最佳结果。(http://kiss-web.blogspot.com/2016/02/memcached-vs-redisphpredis-vs-predis-vs.html)。

我个人认为 Cache::remeber 是最好的模式:

class Cache {
    protected $connection;
    public function __construct($options) {
        $this->connection = new Client($options);
    }

    public function remember($key, $closure, $expiration = 86400) {

        $result = $this->connection->get($key);

        if($result!==false) {
            return unserialize($result);
        }
        $result = $closure();

        $this->connection->set($key, serialize($result), 'ex', $expiration);

        return $result;
    }
}

现在您的代码将如下所示:

$cacheKey = "table/{$id}";
return $cache->remember($cacheKey, function() use ($id) {
    $this->db->query('SELECT * FROM table WHERE table.id = "'.$id.'" ');
    $query = $this->db->get();
    $result = $query->result_array();
    return $result[0];
});
于 2016-02-15T20:02:10.120 回答