知识屋:更实用的电脑技术知识网站
所在位置:首页 > 编程技术 > PHP编程

PHP缓存使用的一个陷阱

发布时间:2014-09-05 10:57:22作者:知识屋

先看一段代码:
[php]
/**
 * 获取设置信息
 */ 
public function getCoinSetting() { 
    $cache  = Common::getTair(); 
    $ckey   = Common::hashKey("Hello"); 
    $ret    = $cache->get($ckey); 
    if ($ret) return json_decode($ret, true); 
    $taomanyiApiService = $this->_getTmiApiService(); 
    $result = $taomanyiApiService->getCoinSetting(); 
    $cache->set($ckey, json_encode($result), 3600); 
    return $result; 

这是一个使用Tair内存缓存的实例,这段代码中,设置了缓存,缓存时间为3600秒。数据是从Api中获取的,如果这么写会出现什么问题呢?假如:
[php] 
$result = $taomanyiApiService->getCoinSetting(); 

$result获取的数据为空,因为$result数据是从HTTP请求过来的,数据不正常也是比较常见的事情。在这种状况下,HTTP请求失败,那么接口数据就请求不到,接下来的流程是设置缓存
[php ]
$cache->set($ckey, json_encode($result), 3600); 

我们会发现,因为一次接口HTTP请求的失败,我们不小心将空数据缓存了起来,缓存时间为3600秒。这样就会出现页面上,例如分类出现了数据的空白,影响了整个业务流程
我们做以下的优化:
[php] 
if ($result) $cache->set($ckey, json_encode($result), 3600);  


作者:initphp
(免责声明:文章内容如涉及作品内容、版权和其它问题,请及时与我们联系,我们将在第一时间删除内容,文章内容仅供参考)
收藏
  • 人气文章
  • 最新文章
  • 下载排行榜
  • 热门排行榜