静态化处理
# 动态语言静态化
# 什么是动态语言静态化?
将现有的PHP等静态语言生成的数据生成为HTML,用户访问动态脚本重定向到HTML文件的过程。一般是对实时性要求不高的页面进行动态语言静态化。
# 为什么要静态化?
- 动态脚本通常会做逻辑计算和数据查询,访问量越大,服务器的压力会越大
- 访问量大时可能会造成CPU负载过高,数据库服务器压力过大
- 静态化可以减低逻辑处理能力,降低数据库服务器的查询压力
# 静态化的实现方式
# 使用模版引擎
使用Smarty的缓冲机制生成静态HTML缓冲文件
// 缓冲目录
$smarty->cache_dir = $ROOT."/cache";
// 是否开启缓冲
$smarty->caching = true;
// 缓冲时间
$smarty->cache_lifetime = 3600;
// 渲染页面
$smarty->display(string template[,string cacheid,string compile_id]);
// 清除所有缓冲
$smarty->clear_all_cache();
// 清除指定的缓冲
$smarty->clear_cache('file.html');
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 使用ob系列函数
// 打开输出控制缓冲
ob_start();
// 返回输出缓冲区内容
ob_get_contents();
// 清空输出缓冲区
ob_clean()
// 冲刷出输出缓冲区并关闭缓冲
ob_end_flush()
// 可以判断文件的修改时间,判断是否过期
filectime()
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 代码示例
<?php
ob_start();
$cache_file = md5(__FILE__)."html";
$cache_lifetime = 3600;
if (filectime(__FILE__) <= filectime($cache_file) && file_exists($cache_file) && filectime($cache_file) + 3600 > time() ) {
include $cache_file;
exit;
}
?>
<b>this is html content</b>
<?php
$contents = ob_get_contents();
ob_end_flush();
$handle = fopen($cache_file,'w');
fwrite($handle,$contents);
fclose();
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上次更新: 2020/12/31, 06:55:18