首先说明我遇到的情况。
有关于访问第三方资源的apigetToken
,生成令牌及令牌过期时间
反应:
token
expired_time
我们希望通过设置缓存来防止429(请求过多)错误。
我们有两个版本。
版本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'];
/p> 我的朋友告诉我版本2更好。 但是我对 为什么我需要计算ttl和删除密钥,特别是如果memcache已经过期的关键?$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'];
$memcache->delete($cacheKeyName);
部分感到困惑。
如果您在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'];