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

用于 linux 执行 crontab 命令生成缓存的文件 crop.php

 1 <?php
 2 //让crontab 定时执行的脚本程序
 3 require_once 'db.php';
 4 require_once 'file.php';
 5 
 6 $sql = 'select * from review where is_enabled = 1 order by creation_time desc limit 6';
 7 try{
 8     $connect = DB::getInstance()->connect();
 9 }catch(Exception $e){
10     //如果捕获异常,记录错误日志
11     file_put_contents('logs/'.date('Y-m-d').'.txt',$e->getMessage());
12     return; 
13 }
14 $res = mysql_query($sql,$connect);    
15 $vals = array();
16 while($val = mysql_fetch_assoc($res)){
17     $vals[] = $val; //二维数组
18 }
19 //加入缓存
20 $file = new Cache();
21 if($vals){
22     $file->cacheData('index-cron_cache',$vals);
23 }else{
24     file_put_contents('logs/'.date('Y-m-d').'.txt','没有相关数据');
25     return;
26 }

注意捕获数据库连接的异常时,应该记录在日志文件中。

 

测试缓存的文件 list2.php

 

 1 <?php
 2 require_once 'response.php';
 3 require_once 'file.php';
 4 
 5 $file = new Cache();
 6 $data = $file->cacheData('index-cron_cache');
 7 //如果获取到数据,则生成接口数据
 8 if($data){
 9     return Response::show(200,'获取缓存成功',$data);
10 }else{
11     return Response::show(400,'首页数据获取失败',$vals);
12 }

 

posted @ 2018-11-22 14:25  L1230205  阅读(436)  评论(0编辑  收藏  举报