首页 > 解决方案 > 对使用 memcache 感到困惑并比较哪种解决方案更好

问题描述

先说明一下我遇到的情况。

有一个getToken关于访问第三方资源的api,它会生成token和token的过期时间。

回应如:

  token
  expired_time

我们希望通过设置缓存来防止 429 (too many request) 错误。

我们有两个版本。

版本 1

$cache = $memcache->get($cacheKey);
if ($cache) {
  return $cache['token'];
}


// Same as code 2.
$tokenResponse = $this->getToken();
$ttl = strtotime($tokenResponse['expired_time']) - strtotime('now');
if ($ttl > 0) {
    $memcache->set($cacheKey, $tokenResponse, $ttl);
} else {
    throw new Exception('error');
}

return $httpResponse['token'];        

第 2 版

$cache = $memcache->get($cacheKey);
if ($cache) {
  $ttl = strtotime($cache['expired_time']) - strtotime('now');
  if ($ttl > 0) return $cache['token'];
  $memcache->delete($cacheKey);
}

// Same as code 1.
$tokenResponse = $this->getToken();
$ttl = strtotime($tokenResponse['expired_time']) - strtotime('now');
if ($ttl > 0) {
    $memcache->set($cacheKey, $tokenResponse, $ttl);
} else {
    throw new Exception('error');
}

return $httpResponse['token'];  


我的朋友告诉我version2更好。

但我对$memcache->delete($cacheKeyName);部分感到困惑。

为什么memcache中key已经过期了,为什么还要计算ttl并删除key?</p>

标签: phpmemorycache

解决方案


如果你在 memchache 中正确设置了 ttl,它不会在过期时间后返回值。所以,没有必要删除它,因为没有什么可以删除的!我不知道您的代码的确切逻辑,但这应该可行:

$cache = $memcache->get($cacheKey);
if (!$cache) {
  $tokenResponse = $this->getToken();
  $ttl = strtotime($tokenResponse['expired_time']) - strtotime('now');
  $memcache->set($cacheKey, $tokenResponse, $ttl);
  return $tokenResponse['token'];
}
return $cache['token'];

推荐阅读