2

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

我想要一个块来呈现我从外部服务检索的信息。由于该块是为许多用户呈现的,我不想不断地从该服务请求数据,而是缓存结果。但是,这个数据变化比较频繁,所以我想每隔 5 或 10 分钟检索一次最新的数据,然后再次缓存。

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

4

3 回答 3

4

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

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

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

于 2011-02-01T15:40:13.230 回答
2

函数cache_set()cache_get()是您正在寻找的。cache_set() 有一个 expire 参数。

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

<?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;
?>

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

于 2011-01-28T14:30:20.157 回答
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;
}
于 2014-01-09T17:56:51.823 回答