Drupal 7临时缓存项目不会过期

Cod*_*er1 6 php drupal drupal-7

我有一个相当昂贵的服务器调用,我需要缓存30秒.然而,似乎我无法使缓存过期.

在下面的代码中,在第一次缓存之后,即使在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;
}
Run Code Online (Sandbox Code Playgroud)

Cli*_*ive 10

你的代码没有任何问题,我认为问题在于cache_set行为方式.在docs页面中,传递UNIX时间戳:

指示该项应至少保留到给定时间,之后它的行为类似于CACHE_TEMPORARY.

CACHE_TEMPORARY 表现如下:

指示应在下一个常规缓存擦除时删除该项目.

我最好的猜测是,因为你没有隐式强制通用缓存擦除(使用cache_clear_all())缓存对象将保持不变.

我认为一个简单的方法就是在缓存检查后手动测试到期时间,如果缓存对象已经过期,则让它重新设置:

if ($cache = cache_get($cid, 'cache_mymodule')) {
  if ($cache->expire > REQUEST_TIME) {
    return $cache->data;
  }
}
Run Code Online (Sandbox Code Playgroud)