php - MVC 中的缓存调用去哪里

标签 php caching redis predis

所以我正在将 Redis 添加到一个已经开发的项目中,我想知道将这些缓存调用放在哪里。 有现有的模型,我想知道我是否可以将 redis 注入(inject)模型,然后用缓存代码包装每个查询,如下所示:

$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);

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

最佳答案

您应该首先分析您的应用程序,找出哪些部分最常被调用,哪些部分最慢。

如果缓存整个 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];
});

关于php - MVC 中的缓存调用去哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386139/

相关文章:

php - MySQL View 查询优化

c++ - 如何通过 IO 时序测量找到 L1 缓存线大小的大小?

caching - 使用 kaniko 构建多阶段图像时出现缓存问题

node.js - 将 backbone.js 与 socket.io 一起使用

sockets - Laravel Forge 队列 worker

PHP:帮助执行一系列查询

php - 多个重复查询 - Laravel

javascript - jquery 无法正确读取 PHP json_encode() 函数

c# - 大对象缓存

redis hscan 命令无法限制计数