php是最好的语言

php之页面静态缓存

页面静态缓存,第一次访问把数据读取出来,渲染静态页面,然后把最后的html数据放在指定的缓存文件中,第二次访问,可以根据时间或者操作来判断是重新读取数据库文件还是直接使用第一次缓存好的HTML文件。方便理解下面是tp5自己写的代码,tp5自带了缓存。

controller:

    

<?php

namespace app\index\controller;

use think\Controller;

use think\Db;

use app\index\model\Detail;

class Details extends Base

{


    public function Index()

    {

        $infoId = input('infoId');

        $category = input('type');


        $flag = $this->is_cache($infoId);//判断缓存是否存在和过期


        if($flag){

            include($this->flag_cache($infoId));//加载缓存文件

            include($this->viewPath.'Detail/tool.html');//点赞、收藏等部分

            exit;

        }

        else{

            $this->ob_start();


            $data = $this->Ajax_json($infoId,$category);//获取数据


            include($this->viewPath.'Detail/details.html');//图片详情部分

            $this->ob_get_contents($this->flag_cache($infoId));//写入缓存


            include($this->viewPath.'Detail/tool.html');//点赞、收藏等部分。此部分没有缓存


        }


    }

    public function Ajax_json($infoId,$category)

    {


        $Detail = new Detail;


        $data = $Detail->detail($infoId,$category);


        return ($data);


    }


}




Base:

    

<?php

namespace app\index\controller;

use think\Controller;

use think\Session;

class Base extends Controller

{

    public $cachePath = 'D:/phpstudy/www/v1/application/index/';//缓存文件夹路径

    public $viewPath = 'D:/phpstudy/www/v1/application/index/view/';//视图路径


    。。。。。



    public function is_cache($infoId)//判断是否有此缓存文件和时间

    {

        $url = $this->flag_cache($infoId);//获取缓存文件名


        return (is_file($url) && (time() - filemtime($url)) < 300)?1:0;

    }


    public function flag_cache($infoId)//获取缓存文件名

    {

        $goods_statis_file = "cache/details".$infoId.".html";


        return $this->cachePath.$goods_statis_file;


    }

    public function ob_start()

    {

        ob_start();

    }    

    public function ob_get_contents($urlName)//写入静态缓存文件

    {

        $content = ob_get_contents();//把详情页内容赋值给$content变量 

        file_put_contents($urlName,$content);//写入内容到对应静态文件中 

        ob_end_flush();//输出商品详情页信息 

    }

}

写得很粗糙,原理基本就是这样。可以利用ab工具测试,吞吐量提高很明显。

作者:xTao 分类:LNMP 浏览:2349 评论:0