如何有效地重新加载缓存数据

时间:2014-07-02 05:44:21

标签: php caching

基本上我会为此缓存所有用户输入数据(例如我将缓存用户注释)。

我正在使用Simple PHP Cache。 现在我要做的就是运行类似(伪代码)的东西:

$cache = new Cache(page-specific-cache);

if(hasNewComments()) {
    $cache->erase('comments');
    $cache->store('comments', array(/*array of comments...*/), 60);
}
//...show comments and stuff

现在我的问题是:我应该运行上面的代码块,还是应该尝试执行类似以下代码的操作,我还会检查缓存是否已过期以及是否已重新生成?在这种情况下,这似乎有点落伍?

$cache = new Cache(page-specific-cache);

if((hasNewComments()) || ($cache->isCached('comments') && $cache->isExpired('comments'))) {
    $cache->erase('comments');
    $cache->store('comments', array(/*array of comments...*/), 60);
}
//...show comments and stuff

备注

isExpired()方法没有附带课程,我自己创建它,这就是它的样子:

public function isExpired($key) {
    if (false != $this->_loadCache()) {
      $cachedData = $this->_loadCache();
      return $this->_checkExpired($cachedData[$key]['time'], $cachedData[$key]['expire']);
    }
  }

1 个答案:

答案 0 :(得分:1)

显然,在尝试使用缓存之前,您正在检查新注释。这使得缓存毫无意义。缓存的重点是从某个系统中获取一些负载(比如不断地从数据库中获取注释),以换取暂时存在过期数据的可能性。你的逻辑应该是这个(伪代码):

comments = cache.get('comments')
if !comments
    comments = database.get('comments')
    cache.store(key='comments', value=comments, expires=3600)

print comments

缓存应该返回false / null /,如果数据之前从未被缓存过,或者它已经过期了。如果您的缓存没有自动到期系统,请使用comments数组保存时间戳,并在获得缓存数据后手动进行检查。

同样,缓存的权衡是,当数据库中已有新数据时,您可能会显示过时的数据。如何以及何时使缓存过期是编程中的两个重大问题之一(另一个是命名内容)。

要么你不关心在一段时间内过时的评论;在这种情况下,明智地选择你的到期时间。

否则,一个好的策略是永远不会让缓存自身过期,但在发布新评论时显式删除缓存。这可确保您始终拥有最新数据,而无需经常检查。但是,如果你的评论频率太高,以至于缓存被永久删除,那么首先要有一个缓存是没有意义的。

这是所有权衡。选择你的甜蜜点。

相关问题