memcache中非常有趣的bug

时间:2012-06-20 12:05:42

标签: php caching memcached

    $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是空的并且没有数据,但是当我重新加载页面时。是否可以在删除缓存时查看网站?

1 个答案:

答案 0 :(得分:1)

必须计时,您需要从缓存中检索两次数据,一次用于检查数据,第二次用于反序列化数据。数据可以在这些调用之间过期,我们无法控制它

只是反序列化您已经获得的数据:

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