PHP 开发 APP 接口--读取缓存方式

以静态缓存为例。

list.php:

 1 <?php
 2 require_once 'response.php';
 3 require_once 'db.php';
 4 require_once 'file.php';
 5 
 6 $page = isset($_GET['page'])?$_GET['page']:1;
 7 $pageSize = isset($_GET['pageSize'])?$_GET['pageSize']:1;
 8 if(!is_numeric($page) || !is_numeric($pageSize)){
 9     return @Response::show(401,'数据不合法');
10 }
11 
12 $offset = ($page-1)*$pageSize; //每页起始数
13 $sql = 'select * from review where is_enabled = 1 order by creation_time desc limit '.$offset.','.$pageSize;
14 $cache = new Cache();
15 $vals = array();
16 //当没有缓存或者缓存失效时,连接数据库并从数据库中取出数据
17 //注意当有分页的数据时,需要把分页信息写入文件名
18 if(!$vals = $cache->cacheData('index-data'.$page.'-'.$pageSize)){
19     //echo 'aaaa';exit(); //测试缓存失效
20     try{
21         $connect = DB::getInstance()->connect();
22     }catch(Exception $e){
23         return Response::show(403,'数据库连接失败');
24     }
25     $res = mysql_query($sql,$connect);    
26     while($val = mysql_fetch_assoc($res)){
27         $vals[] = $val; //二维数组
28     }
29     //同时把取出的数据存入缓存
30     if($vals){
31         $cache->cacheData('index-data'.$page.'-'.$pageSize,$vals,50);
32     }
33 }
34 //如果缓存存在同时没有失效,使用封装的接口类封装缓存中的数据
35 if($vals){
36     return Response::show(200,'首页数据获取成功',$vals);
37 }else{
38     return Response::show(400,'首页数据获取失败',$vals);
39 }

file.php:

 1 <?php
 2 class Cache{
 3     //静态缓存文件后缀名
 4     const EXT = 'txt';
 5     //定义缓存文件存放路径
 6     private $_dir;
 7     public function __construct(){
 8         $this->_dir = dirname(__FILE__).'/files/';
 9     }
10 
11     public function cacheData($k,$v = '',$cacheTime = 0){ //默认永久不失效
12         //文件名
13         $filename = $this->_dir.$k.'.'.self::EXT;
14         //$v不为‘’:存储缓存或者删除缓存
15         if($v !== ''){
16             //删除缓存
17             if(is_null($v)){
18                 return @unlink($filename);
19             }
20             //存储缓存
21             $dir = dirname($filename);
22             if(!is_dir($dir)){
23                 mkdir($dir,0777);
24             }
25             $cacheTime = sprintf('%011d',$cacheTime);    //$cacheTime 设置为11位(方便截取),不满11位前面补0
26             //把缓存时间拼接$v
27             return file_put_contents($filename,$cacheTime.json_encode($v));
28         }
29         //读取缓存
30         if(!is_file($filename)){
31             return false;
32         }
33         $contents = file_get_contents($filename);
34         $cacheTime = (int)substr($contents,0,11);
35         $val = substr($contents,11);
36         if($cacheTime != 0 && $cacheTime+filemtime($filename) < time()){    //缓存已经失效
37             unlink($filename);
38             return false;
39         }
40         return json_decode($val,true);
41     }
42 }

测试 http://127.0.0.17/php/APP/list.php?pageSize=10&page=3 生成 index-data3-10.txt

测试 http://127.0.0.17/php/APP/list.php?pageSize=10 生成 index-data1-10.txt

猜你喜欢

转载自www.cnblogs.com/lxj0205/p/10000786.html