$new = $this->memcache->get("posts");
if(empty($new)){
// Get the new posts
$new = Posts::getNow("10");
// Save them in memcache
$this->memcache->set('posts', serialize($new), 0, 60*3); // Cache time is 3 min
// If we found them in cache - load them from there
} else {
// Get data from memcache
$new = unserialize($this->memcache->get("posts"));
}
如果缓存加载中有数据,则代码非常简单,如果不是再次获取它们。有趣的是,有时当我查看站点时,div 是空的,没有数据,但是当我重新加载页面时,有。当缓存被破坏时,我对站点的看法是否有可能?
那一定是计时,您从缓存中检索数据两次,一次用于检查它是否在这里,第二次用于反序列化它。数据可能仅在这些调用之间过期,我们无法控制它
只需反序列化您已经获得的数据:
$data = $this->memcache->get("posts");
if(empty($data)){
// Get the new posts
$new = Posts::getNow("10");
// Save them in memcache
$this->memcache->set('posts', serialize($new), 0, 60*3);
} else {
// Unserialize data instead of retrieving it from cache for second time.
$new = unserialize($data);
}