【问题标题】:Confused about using memcache and compare which solution is better对使用 memcache 感到困惑并比较哪种解决方案更好
【发布时间】:2021-08-17 06:46:22
【问题描述】:

先说明我遇到的情况。

有一个apigetToken关于访问第三方资源, 它会生成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'];  


我的朋友告诉我版本2更好。

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

如果memcache已经过期key,为什么还要计算ttl并删除key?

【问题讨论】:

  • 我要做的第一件事就是问问你的朋友为什么发表评论,看看他们有什么理由。

标签: php memorycache


【解决方案1】:

如果你在 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'];

【讨论】:

  • 谢谢!你的建议让我知道我的怀疑是对的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 2017-03-20
  • 2012-01-18
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
相关资源
最近更新 更多