Small Ant Learning App Interface Development (7)--app Interface instance--read cache mode code case for developing the app interface

Source: Internet
Author: User
Tags exit in learn php

Reading data directly from a database, while highly-sensitive, is very stressful for the database, especially in the case of high traffic. At this time can be through the cache, to effectively alleviate the pressure, although some lack of timeliness, but the server's ability to resist pressure has reached a great increase.

The central idea of how to read the cache:

When the request comes in, first to see if there is a cache, if any, and the cache is still within the valid time, no longer query the database, directly return to the cache, if not or has been a valid time, query the database, return data, and generate a new cache for later use.

Code case, or in the first few days of code based on the improvement.

File static Cache class (original code please refer to http://my.oschina.net/woshixiaomayi/blog/517876)

Some modifications have been made to change the third parameter in the original CacheData () method from path to Cachetime, which is used to record the valid time of the cache. Added in the method, the logic to write the cache time, and to determine whether the cache file is out of date logic, as follows:

<?php/**********************************    Modify the file class, the cache time parameter is added to the CacheData method *    Learn PHP's little ant *    original blog  http://my.oschina.net/woshixiaomayi/blog****************************/  class file{     //path to cache files     private $_dir;      //default path to cached files     const ext= '. txt ';      //construction method Generate directory     function __construct () {          $this->_dir  =   dirname (__file__). ' /files/';         if (!is_dir ($this->_dir)) {             mkdir ($this->_dir,0777);          }    }     /*************************     *    *    CacheThe file is generated, modified, deleted, and the third parameter is changed to cache time     *    $value have value, write. No value, read out. NULL, delete     *    @param       string          $key     file name          *    @param       mixed      $value       Cached data        *    @param        int         $cacheTime    Valid time for cached files     *   return      mixed          return value is Boolean, String, Integer     *    ***** /    public function cachedata ($key, $value = ", $cacheTime =0) {           &nbFull path          $filename of sp;      //cache files    =    $this->_dir. $key .self::ext;          //if value is null, this deletes this static cache         if (Is_null ($value)) {             return  @unlink ($filename);          }                   //if $value is not equal to NULL, the description is write operation          if ($value  !=  ") {            // Determine if the submitted path exists              $dir    =    dirname ($filename);             if (!is_dir ($dir)) {&NBSP;&NBSp;              mkdir ($dir, 0777);             }             /*                  when a write operation is made, it is included with the cache validity time                   effective time is 11-bit shaping, less than 11 bits in front end with 0 top-up                   this facilitates interception              */$cacheTime =sprintf ('%011d ', $cacheTime);             //will cache valid time stitching data JSON, save to file              Return file_put_contents ($filename, $cacheTime. Json_encode ($value));         }elseif ($value ==  ') {    //description is read operation              if (Is_file ($filename)) {                 /*                      because the cache time is added, they need to be split and judged,                      whether the cache expires, if not expired, returns the data if it expires,                       Delete source file, return false.                 */$content = File_get_contents ($filename);                 //get this file cache for a limited time $time= (int) substr ($content, 0,11);                 /*                      to determine if the cache is available                      1. Determine if the expiration time is a persistent cache (0 is a permanent cache)                      2. The cache time plus whether the file modification time is less than the current time, if less than                       has expired                  */if ($time  != 0 &&  ($time  +  filemtime ($filename)  < time ()) {//cache file not available, delete the file, return to Falseunlink ($filename); return false;} Cache data available, take out data, return directly to $value=substr ($content, one);                &nBsp;return json_decode ($value, True);             }else{                 return false;            }         }     }}?>

In

     logic code, you need to make a decision as to whether a cache file exists. Have and do not expire, then use the cache file, no longer read the database, no or has expired, then go to the steps to query the database, while generating the cache file. The Echo 123 in the code is used for testing, and the comments have been explained.

<?php/************************************* read the database How to develop the homepage interface * Learn php small ant * Blog  http://my.oschina.net/ woshixiaomayi/blog*************************************///loading the DB class//code content written the day before yesterday please refer to  http://my.oschina.net/ Woshixiaomayi/blog/518295require_once ('./db.php ');//Load the previously written interface response class//code contents please refer to  http://my.oschina.net/ Woshixiaomayi/blog/517384require_once ('./response.php ');//load the newly modified file static cache class Require_once ('./file.php ');//Receive paging data  page  for current page   pagesize  page how much data $page=isset ($_get[' page ')? $_get[' page ']:1; $pagesize = Isset ($_get[' pagesize '))? $_get[' pagesize ']:5;//detects if the two values are numeric if (!is_numeric ($page)  or !is_numeric ($ pagesize)) {//Not a number, send an error message */* The reason for using a return here is to enhance the readability of the program, because programmers unfamiliar with the program, do not know that there is exit in the Show method, plus a return, others will know that after the execution of this step, The program will stop and the subsequent program will not execute. Convenient for other people, everyone good is really good \ (^o^)/yes!*/return response::show (400, ' argument not valid ');} Set the offset required for paging $offset= ($page-1) * $pagesize;//write SQL statement $sql= "Select * from ecm_member limit   ". $offset.", ". $pagesize;//Instantiate the file cache class to see if there is a cache file in the valid time $FILE=NEW&NBSp File (); if (! $index _data= $file->cachedata (' list '. $page. ' _ '. $pagesize)} {/* Here for debugging, 123 of,echo  at first access, then access, because the cache has been generated, no longer take this step, so 123 does not appear. It's not until the time is up. */echo 123;//if there is an error connecting to the database, get the information, and return the customized information//To avoid exposing the error directly to the user try{$connect  =db::getinstance ( )->connect ();} catch (exception  $e) {//error message returned to App Return response::show (' Mysql not connect ');} The database connection succeeds, executes the SQL statement, gets the result set $result=mysql_query ($sql, $connect); $index _data=array (); while ($row =mysql_fetch_assoc ($ Result) {$index _data[]= $row;} $file->cachedata (' list '. $page. ' _ '. $pagesize, $index _data,15);} if ($index _data) {//required result data to get, return data return response::show (200, ' content obtained successfully ', $index _data);} else{//not get, return error prompt Return response::show (400, ' Home data acquisition failed '); >

Read cache The idea of developing an interface is basically like this, very well understood, but here is the most stupid method, in the form of local save file cache, can actually use some more advanced services, such as Memcache, Redis and other cache, more efficient, time, Use these two services to test again ~ (~ ̄▽ ̄) ~ Add an oil.

Small Ant Learning App Interface Development (7)--app Interface instance--read cache mode code case for developing the app interface

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.