A trap used by PHP Cache

Source: Internet
Author: User

First look at a piece of code:
[Php]
/**
* Get settings
*/
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 instance that uses Tair memory cache. In this Code, cache is set to 3600 seconds. The data is obtained from the Api. What will happen if the data is written like this? Suppose:
[Php]
$ Result = $ taomanyiApiService-> getCoinSetting ();

The data obtained by $ result is null, because $ result data is obtained from an HTTP request, and abnormal data is also a common issue. In this case, the HTTP request fails, and the interface data cannot be requested. The next process is to set the cache
[Php]
$ Cache-> set ($ ckey, json_encode ($ result), 3600 );

We will find that due to an HTTP request failure, we accidentally cache the empty data for 3600 seconds. In this way, the page appears. For example, the blank data in the category affects the entire business process.
We have made the following optimizations:
[Php]
If ($ result) $ cache-> set ($ ckey, json_encode ($ result), 3600 );


Author: initphp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.