2011-11-13 19 views
6

我有一个相当昂贵的服务器调用,我需要缓存30秒。但似乎我无法让缓存过期。Drupal 7临时缓存项目不会过期

在下面的代码中,第一次缓存后,即使在time()+ 30秒之后,也不会超过$ return-> cache_data。

请注意,我甚至可以打印$ cache-> expire,它肯定会设置为30秒前的时间,并且不会更新。

我已经手动清除缓存很多次,以确认我得到相同的结果。

这样看起来有什么不对吗?

function mymodule_get_something($id) { 
    // set the unique cache id 
    $cid = 'id-'. $id; 

    // return data if there's an un-expired cache entry 
    // *** $cache ALWAYS gets populated with my expired data 
    if ($cache = cache_get($cid, 'cache_mymodule')) { 
    return $cache->data; 
    } 

    // set my super expensive data call here 
    $something = array('Double Decker Taco', 'Burrito Supreme'); 

    // set the cache to expire in 30 seconds 
    cache_set($cid, $something, 'cache_mymodule', time() + 30); 

    // return my data 
    return $something; 
} 

回答

10

没有什么不对您的代码,这样,我认为这个问题是如何cache_set的行为。从docs page,传递一个UNIX时间戳:

表示该项目应至少保存到指定的时间后,它的行为就像CACHE_TEMPORARY。

CACHE_TEMPORARY的行为是这样的:

表示该项目应在下届缓存擦拭去除。

我最好的猜测是,因为你不是暗中强制通用缓存擦除(使用cache_clear_all())缓存对象将会持续存在。

我认为它周围的一个简单的方法也只是缓存检查之后手动测试的终止时间,让它落空要重新设置高速缓存对象,如果它已经过期:

if ($cache = cache_get($cid, 'cache_mymodule')) { 
    if ($cache->expire > REQUEST_TIME) { 
    return $cache->data; 
    } 
} 
+0

感谢健康检查。 – Coder1

+1

好方法。 +1 ...编辑:只是注意到它是克莱夫。当然这是一个好方法。 –

+0

Hello Clive,“下一般缓存擦除”是什么? drush cc all会删除CACHE_TEMPORARY和CACHE_PERMANENT。当一般缓存刷卡发生时,有什么想法? –