Home > Backend Development > PHP Tutorial > A pitfall in using PHP cache_PHP Tutorial

A pitfall in using PHP cache_PHP Tutorial

WBOY
Release: 2016-07-13 17:53:02
Original
848 people have browsed it

Look at a piece of code first:
[php]
/**
* Get setting information
​*/
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;
}

This is an example of using Tair memory cache. In this code, the cache is set and the cache time is 3600 seconds. The data is obtained from the API. What problems will occur if it is written like this? If:
[php]
$result = $taomanyiApiService->getCoinSetting();

The data obtained by $result is empty because the $result data is requested from HTTP. It is also common for the data to be abnormal. In this case, the HTTP request fails, so the interface data cannot be requested. The next process is to set up the cache
[php ]
$cache->set($ckey, json_encode($result), 3600);

We will find that due to the failure of an interface HTTP request, we accidentally cached empty data, and the cache time is 3600 seconds. This will appear on the page, for example, there will be data gaps in the classification, affecting the entire business process
We make the following optimizations:
[php]
if ($result) $cache->set($ckey, json_encode($result), 3600);


Author: initphp

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478077.htmlTechArticleLook at a piece of code first: [php] /*** Get setting information*/ public function getCoinSetting() { $cache = Common::getTair(); $ckey = Common::hashKey(Hello); $ret = $cache-get($ckey); if...
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