基本的思路:服务器只负责定时更新缓存。请求进来只需要读取缓存就可以了。
服务器定时执行生成缓存的代码:
<?php
/********************************
*
* crontab 定时生成缓存文件
* * * * * * /usr/bin/php /app/crontab.php
* 学php的小蚂蚁
* 原创博客 http://my.oschina.net/woshixiaomayi/blog
*
***************************/
//载入前天写的db类
//代码内容请参考 http://my.oschina.net/woshixiaomayi/blog/518295
require_once('./db.php');
//载入之前写好的文件静态缓存类
//代码内容请参考 http://my.oschina.net/woshixiaomayi/blog/518885
require_once('./file.php');
try{
$connect = Db::getInstance()->connect();
}catch(Exception $e){
/*
因为这里是让crontab定时执行的,错误只能写到错误日志之中,
这一点一定要注意一下。
*/
file_put_contents('./log/'.date('Y-m-d').'.txt', $e->getMessage());
return;
}
//操作数据库
$sql="select * from ecm_member limit 3";
$result = mysql_query($sql,$connect);
$index_data=array();
while ($row = mysql_fetch_assoc($result)) {
$index_data[] = $row;
}
//实例化静态文件缓存类,得到数据就缓存,没有则写入日志
$file = new file();
if($index_data){
$file->cacheData('index_page',$index_data);
}else{
file_put_contents('./log/'.date('Y-m-d').'.txt', '没有获取数据');
}
?>
请求进来,直接将crontab生成的缓存发送给用户即可:
<?php
/************************************
*
* 调用crontab定时生成的缓存数据
* 学php的小蚂蚁
* 博客 http://my.oschina.net/woshixiaomayi/blog
*
******************************/
//载入之前写好的接口响应类
//代码内容请参考 http://my.oschina.net/woshixiaomayi/blog/517384
require_once('./response.php');
//载入之前写好的接口响应类
//代码内容请参考 http://my.oschina.net/woshixiaomayi/blog/518885
require_once('./file.php');
//有访问进来,读取缓存,crontab会定时更新缓存,所以直接使用就行了
$file = new File();
$data = $file -> cacheData('index_page');
if($data){
return Response::show(200,'数据返回成功',$data);
}else{
return Response::show(400,'数据返回失败');
}
?>
这个思路上也比较简单,APP接口实例到这里接学习结束了。 b( ̄▽ ̄)d 加油!
来源:oschina
链接:https://my.oschina.net/u/1423209/blog/519210