3

我正在使用 Zend_Cache 缓存从 Web 服务生成的数据。但是,如果 Web 服务没有响应,我想显示过时的信息而不是留下空白。

根据文档,答案是将第二个参数传递给Zend_Cache_Core::load()

@param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested

但是,对于我所做的每一个测试,这总是返回bool(false)过期的缓存内容。

有没有办法强制 Zend_Cache 返回给定缓存键的缓存数据,即使它已经过期?

$cache_key = md5($url);
if ($out = $cache->load($cache_key)) {
  return $out;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);

if ($output) {
  // Process...
  $cn_cache->save($out, $cache_key);
} else {
  // The query has timed out/web service not responded
  // We need to load the outdated cached content... but the following DOES NOT work
  return $cache->load($cache_key, true);

  // var_dump($cache->load($cache_key, true)); # false
}
4

1 回答 1

1

除了拥有永不过期的对象的第二个缓存版本之外,我想不出一种可靠的方法来做到这一点。如果您在对象上设置 X 秒的缓存过期时间,则根本无法保证该对象在 X 秒后仍然存在。

下面建议的解决方法示例...

...
$cache_key_forever = sha1($url)
if ($output) {
  // Process...
  $cn_cache->save($out, $cache_key);
  $cn_cache->save($out, $cache_key_forever, array(), null); // The "null" parameter is the important one here: save cache indefinitely
} else {
  // The query has timed out/web service not responded
  // Load the infinitely persisted cache object
  return $cache->load($cache_key_forever);

  // var_dump($cache->load($cache_key, true)); # false
}
于 2012-01-29T09:03:24.537 回答