您的位置:首页 > 其它

夺命雷公狗---Smarty NO:24 缓存控制技术1

2015-12-09 17:20 239 查看

什么是缓存技术

IE缓存:就是把请求的数据放入IE等浏览器中(客户端缓存)

HTML+CSS+JS+IMG

Smarty缓存:服务器端缓存

2、服务器缓存应用

1)减少服务器I/O

2)减少数据库服务器压力

3)减少服务器访问时间,加快反应速度

编译技术 < 缓存技术 < 静态技术(不方便管理)

3、Smarty缓存机制

$smarty->setCacheDir($cache_dir); //设置缓存目录(默认为cache)

$smarty->caching=true; //开启缓存开关

$smarty->cache_lifetime=3600; //设置默认生命周期

示例代码:

//初始化信息(读取数据,设置默认路径)
$smarty -> caching = true;//默认为false,如果要使用必须开启缓存开关
$smarty -> cache_lifetime = 3600;//单位为毫秒


4、缓存生命周期与缓存运行机制

1)缓存从何而来

说明:当我们删除缓存文件时,然后修改编译文件,重新访问同一页面时,系统会重新生成缓存文件,通过结果发现,缓存是由编译文件直接生成的。

2)缓存文件什么时候会自动更新

① 当缓存的生命周期过期时,系统将重新生成缓存

② 当模板发生变化时,缓存文件也会重新生成

5、缓存原理图



6、缓存的判断

1)缓存可以减少对数据库服务器的访问,减少数据库服务器的压力

通过以下方法即可解决

<?php
header(“Content-Type:text/html;charset=utf-8″);
require “smarty/Smarty.class.php”;
$smarty = new Smarty();
//初始化信息(读取数据,设置默认路径) $smarty -> caching = true;//默认为false,如果要使用必须开启缓存开关 $smarty -> cache_lifetime = 3600;//单位为毫秒
if($smarty->isCached(“demo7.html”)){
$smarty -> display(“demo7.html”);
exit;
}
echo “hello”;
mysql_connect(“localhost”,’root’,”);
mysql_query(“use xsphp”);
mysql_query(‘set names utf8′);
$sql = “select * from stu where id=100″;
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$smarty -> assign(‘row’,$row);
$smarty -> display(“demo7.html”);


运行以上代码可知,只有当我们第一次访问网址时,系统会输出hello,以后每次访问系统将自动转向缓存文件,从而达到减少数据库访问目的。

7、删除缓存

$smarty->clearCache(“tpl”):删除指定页面的缓存

$smarty->clearAllCache():删除所有页面的缓存

示例代码:

//定义一个函数,专门用于清理缓存,一般放置于管理系统的右上角
$smarty -> clearCache(“demo7.html”);//删除demo7页面缓存
$smarty -> clearAllCache();//删除所有缓存(管理系统右上角按钮)

8、单页面多缓存

http://localhost/20150602/demo08_cache.php?id=485

http://localhost/20150602/demo08_cache.php?id=489

http://localhost/20150602/demo08_cache.php?id=500

通过运行以上网址可知,只有当我们运行第一个页面时,系统才能正常显示,以后每次运行都自动显示第一次的执行结果。

如果解决以上问题?

答:可以通过以下方式解决(单页面多缓存)

$smarty->display(“tpl”, “cacheid”);我们可以把经常变化的变量放入display函数的第二个参数中,即可解决以上问题。

$smarty -> display(“demo7.html”,$id);

单页面多缓存一般用于内容页或详细页
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: