在Drupal中创建一个定时缓存

时间:2011-01-28 12:24:32

标签: drupal caching drupal-7

我正在寻找有关如何在Drupal 7中获得以下缓存行为的更多详细信息。

我想要一个呈现我正在从外部服务检索的信息的块。当为许多用户呈现块时,我不希望不断地从该服务请求数据,而是缓存结果。但是,这些数据的更改频率相对较高,所以我想每5或10分钟检索一次最新数据,然后再次缓存。

有没有人知道如何在不自己编写太多代码的情况下实现这种缓存行为?关于如何在Drupal(7)中使用缓存的良好文档方面,我也没有找到太多内容,所以任何关于它的指针都会受到赞赏。

3 个答案:

答案 0 :(得分:3)

请记住,cache_get()实际上并不会检查项目是否已过期。所以你需要使用:

if (($cache = cache_get('your_cache_key')) && $cache->expire >= REQUEST_TIME) {
  return $cache->data;
}

还要确保在D7中使用REQUEST_TIME常量而不是time()。

答案 1 :(得分:2)

您正在寻找的功能cache_set()cache_get()。 cache_set()有一个过期参数。

你可以基本上像这样使用它们:

<?php
if ($cached_data = cache_get('your_cache_key')) {
  // Return from cache.
  return $cached_data->data;
}

// No or outdated cache entry, refresh data.
$data = _your_module_get_data_from_external_service();
// Save data in cache with 5min expiration time.
cache_set('your_cache_key', $data, 'cache', time() + 60 * 5);
return $data;
?>

注意:您还可以使用不同的缓存bin(请参阅文档链接),但您需要自己创建相应的缓存表作为模式的一部分。

答案 2 :(得分:0)

我认为这应该是$cache->expire,而不是过期。如果我在REQUEST_TIME + 300中设置cache_set(),我就没有运气这个例子,因为$cache->expires总是小于REQUEST_TIME。这对我有用:

if (($cache = cache_get('your_cache_key', 'cache')) && (REQUEST_TIME < $cache->expire)) {
  return $cache->data;
}