php - 对使用 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>
解决方案
如果你在 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'];
推荐阅读
- jquery - 单击按钮时,循环浏览 div 列表并切换可见性
- java - 以编程方式访问解析上下文之外的 ANTLr 语法规则字符串文字
- python - Python Selenium - 找不到提交按钮
- html - React JS 将元素渲染到我的 Django 应用程序中只有一个 html 页面的 Dom
- scala - 在scala中逐个单元格比较2 spark数据帧
- swift - 从 session.dataTask 调用中获取错误代码和描述
- wpf - 如何 OneWayBind 到 materialDesign:ButtonProgressAssist.IsIndicatorVisible DependencyProperty
- sql - 需要帮助来理解查询的 SUM(CASE 部分
- jquery - Jquery中的.each()不返回结果
- c - 相对于函数开头的 __LINE__ 宏的等价物