现在的网站一般都需要与数据库进行打交道访问量较大时会对数据库造成很大的压力将一些动态页面执行的结果进行缓存当下次进行访问时直接访问缓存可以减少对数据库的压力同时也可以加快服务器的响应速度缓存的结果可以存放到外存上也可以存在内存中在下一次访问该页面时直接从外存(内存)中直接读取上次的结果
[php]
<?php
//首先查看缓存文件
if(file_exists(l)){
//缓存时间为分钟
if(time()filemtime(l)<*){
//将静态文件内容返回给客户端
$start_time = microtime();
echo 我是从静态文件中读取的数据:<br/>;
echo file_get_contents(l);
$end_time = microtime();
echo 静态文件使用时间:($end_time$start_time);
exit;
}
}
//如果是首次访问或者是上次缓存的时间超过分钟则从数据库中读取数据
$host = ;
$user = root;
$password = ;
//记录开始时间
$start_time = microtime();
mysql_connect($host$user$password);
mysql_select_db(mydb);
mysql_query(set names utf);
$sql = SELECT nameaddressemail FROM users;
$resource = mysql_query($sql);
echo 我是从数据库中读取的数据:<br/>;
ob_start();//打开输出缓沖
echo <table border=><tr><th>姓名</th><th>地址</th><th>Email</th></tr>;
//输出取得的信息
while($userInfo = mysql_fetch_assoc($resource)){
echo <tr>;
echo <td>$userInfo[name]</td>;
echo <td>$userInfo[address]</td>;
echo <td>$userInfo[email]</td>;
echo </tr>;
}
$end_time=microtime();
$str=ob_get_contents();//获取缓沖区的内容
ob_end_flush();
echo 从数据库读数据的时间:($end_time$start_time);
file_put_contents(l$str);
?>
<?php
//首先查看缓存文件
if(file_exists(l)){
//缓存时间为分钟
if(time()filemtime(l)<*){
//将静态文件内容返回给客户端
$start_time = microtime();
echo 我是从静态文件中读取的数据:<br/>;
echo file_get_contents(l);
$end_time = microtime();
echo 静态文件使用时间:($end_time$start_time);
exit;
}
}
//如果是首次访问或者是上次缓存的时间超过分钟则从数据库中读取数据
$host = ;
$user = root;
$password = ;
//记录开始时间
$start_time = microtime();
mysql_connect($host$user$password);
mysql_select_db(mydb);
mysql_query(set names utf);
$sql = SELECT nameaddressemail FROM users;
$resource = mysql_query($sql);
echo 我是从数据库中读取的数据:<br/>;
ob_start();//打开输出缓沖
echo <table border=><tr><th>姓名</th><th>地址</th><th>Email</th></tr>;
//输出取得的信息
while($userInfo = mysql_fetch_assoc($resource)){
echo <tr>;
echo <td>$userInfo[name]</td>;
echo <td>$userInfo[address]</td>;
echo <td>$userInfo[email]</td>;
echo </tr>;
}
$end_time=microtime();
$str=ob_get_contents();//获取缓沖区的内容
ob_end_flush();
echo 从数据库读数据的时间:($end_time$start_time);
file_put_contents(l$str);
?>
users表中有三条记录使用的是apache服务测试结果如下
从数据库中读数据其平均执行时间为:s左右
直接读缓存文件期平均执行时间为:
数据库中的记录只有三条SQL也是简单的单表查询当表的中记录很多时或者是多表查询其执行的时间将会更长缓存虽然能够减少访问数据库的次数加速响应时间但缓存并不适合所有的页面有些页面可能每次访问时其页面的显示的内容就会发生变化这样的页面显然不能使用缓存对于那些变化很少的页面才比较适合使用缓存