【发布时间】: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