ge"/> ge">

PHP缓存应用的一个陷阱

WBOY
Release: 2016-06-13 13:23:33
Original
892 people have browsed it

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;
	}
Copy after login


这是一个使用Tair内存缓存的实例,这段代码中,设置了缓存,缓存时间为3600秒。数据是从Api中获取的,如果这么写会出现什么问题呢?假如:

$result = $taomanyiApiService->getCoinSetting();
Copy after login


$result获取的数据为空,因为$result数据是从HTTP请求过来的,数据不正常也是比较常见的事情。在这种状况下,HTTP请求失败,那么接口数据就请求不到,接下来的流程是设置缓存

$cache->set($ckey, json_encode($result), 3600);
Copy after login


我们会发现,因为一次接口HTTP请求的失败,我们不小心将空数据缓存了起来,缓存时间为3600秒。这样就会出现页面上,例如分类出现了数据的空白,影响了整个业务流程

我们做以下的优化:

if ($result) $cache->set($ckey, json_encode($result), 3600); 
Copy after login


 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template