您的位置:首页 > 编程语言 > PHP开发

三,PHP缓存机制实现页面静态化

2016-08-03 11:47 603 查看
页面静态化思路:

因为新闻这种信息对实时性要求不高,并且比较稳定,所以可以这样做:当地一个用户访问某条新闻后,我们使用ob缓存机制,将内容缓存到html页面。当下一次访问时候,直接访问html页面。这样减少访问数据库次数,提高程序的效率,但是如果新闻内容修改,html静态页面必须实时改变,此处将html静态页面设定30s的过期时间,这样确保hrml静态页面和新闻的一直性,但是有30s延迟,没法保证实时性。

程序代码如下:

(1)数据库操作的类文件 ConnDB.class.php

<?php
/**
* Created by PhpStorm.
* User: 58
* Date: 2016/8/5
* Time: 8:57
*/
class ConnDB{
private static $host = '127.0.0.1';
private static $username = 'root';
private static $password = '7758521Lhy';
private static $db = 'test';
private $conn = null;

public function __construct(){
$this->conn = new MySQLi(self::$host,self::$username,self::$password,self::$db);
if(!$this->conn){
echo '数据库连接错误:'.$this->conn->connect_error;
exit();
}
$this->conn->query("set names utf-8");
}

public function execute_dql($sql){
$rs = $this->conn->query($sql) or die('查询出错!'.$this->conn->error);
$rsList = array();
if($rs){
while($row = $rs->fetch_assoc()){
$rsList[] = $row;
}
}
$rs->free();
return $rsList;
}

public function execute_dml($sql){
$rs = $this->conn->query($sql);
if(!$rs){
$flag = 0;
}else if($this->conn->affected_rows){
$flag = 1;
}else{
$flag = 2;
}
return $flag;
}

public function clossDB(){
if($this->conn){
$this->conn->close();
}
}
}


(2)新闻列表显示页面 news_list.php

<?php
/**
* Created by PhpStorm.
* User: 58
* Date: 2016/8/5
* Time: 15:31
*/
header("Content-Type:text/html;charset=utf-8");
require_once "ConnDB.class.php";
$conn = new ConnDB();
$sql = "select * from news";
$rs = $conn->execute_dql($sql);
$conn->clossDB();
ob_start();
echo "
<a href='add_news.php'>发布文章</a>
<table border='1'>
<tr><th>id</th><th>标题</th><th>详细内容</th></tr>";

foreach($rs as $row){
echo "<tr><td>{$row['id']}</td><td>{$row['title']}</td><td><a href='show_news.php?id={$row['id']}'>详细内容</a></td></tr>";
}
echo "
</table>
";


  

(3)单条新闻显示页面show_news.php

<?php
/**
* Created by PhpStorm.
* User: 58
* Date: 2016/8/5
* Time: 9:40
*/
header("Content-Type:text/html;charset=utf-8");
$id = $_GET['id'];
$html_filename = "news_id".$id.".html";
//新闻如果更新,静态页面无法更新,可以设定静态页面过期时间30s,这样30s后,重新生成新的静态页面,
//这样保证静态页面和新闻的一致性,但是没法确保实时性
if(file_exists($html_filename) && filemtime($html_filename)+30 > time()){
echo file_get_contents($html_filename);
exit();
}
require_once "ConnDB.class.php";
$conn = new ConnDB();
$sql = "select * from news where id = {$id} limit 1";
$rs = $conn->execute_dql($sql);
$conn->clossDB();
if($rs){
ob_start();
$row = $rs[0];

echo "
<table border='1'>
<tr><th>{$row['title']}</th></tr>
<tr><td>{$row['content']}</td></tr>
</table>
";
$html_contents = ob_get_contents();
$html_header = "<head><meta http-equiv='content-type=text/html;charset=utf-8'></head>";

file_put_contents($html_filename,$html_header.$html_contents);
}


  

  

单纯使用缓存技术存在的不足:

(1)news_list.php中点击“详细内容”时候,跳转到html静态页面时候,显示php页面。比如打开news_id1.html页面时候,地址栏显示http://127.0.0.1/show_news.php?id=1

(2)实时性不完美,存在30s延时。

可以使用真静态技术解决此问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐