zoukankan      html  css  js  c++  java
  • 动态语言静态化

    什么是动态语言静态化?

    将现有PHP等动态语言的逻辑代码生成为静态HTML文件,用户访问动态脚本重定向到静态HTML文件的过程。
    对实时性要求不高的页面。

    为什么要静态化?

    • 动态脚本通常会做逻辑计算和数据查询,访问量越大,服务器压力越大
    • 访问量大时可能会造成CPU负载过高,数据库服务器压力过大
    • 静态化可以降低逻辑处理压力,降低数据库服务器查询压力

    静态化的实现方式

    一、使用模板引擎 - Smarty

    利用Smarty的缓存机制生成静态HTML缓存文件

    //config
    $smarty->cache_dir = $ROOT.'/cache';//缓存目录
    $smarty->caching = true;//是否开启缓存
    $smarty->cache_lifetime = "3600";//缓存时间
    //display
    $smarty->display(template[, cache_id[, compile_id]]):
    //clear
    $smarty->clear_all_cache();//清除所有缓存
    $smarty->clear_cache('file.html');//清除指定的缓存
    $smarty->clear_cache('article.html', $arti_id);//清除同一个模板下的指定缓存ID的缓存
    

    二、使用ob系列函数

    //相关函数
    ob_start()://打开输出控制缓冲
    ob_get_contents()://返回输出缓冲区内容
    ob_clean()://清空输出缓冲区
    ob_end_flush()://冲刷出缓冲区内容并关闭缓冲
    

    判断是否过期使用文件的inode修改时间,可用PHP里的 filectime() 函数。
    示例如下:

     <?php
    $id = $_GET['id'];
    $cache_name = md5(__FILE__).'-'.$id.'.html';
    $cache_lifetime = 3600;
    if(filectime(__FILE__) <= filectime($cache_name) && file_exists($cache_name) && filectime($cache_name) + 3600 > time()){
      include $cache_name;
      exit;
    }
    ob_start();
     ?>
     <b>This is My Great Wall id = <?php echo $id ?></b>
     <?php
    $content = ob_get_contents();
    ob_end_flush();
    $handle = fopen($cache_name, 'w');
    fwrite($handle, $content);
    fclose($handle);
    ?>
    
  • 相关阅读:
    nginx-syslog
    loki
    idea安装中文插件
    nginx虚拟目录alias
    个人 软件系统整理
    Python 遍历Sheet 每个Sheet都单独保存为一个Excel
    SQL Server 多表关联的update语句
    电商 生意参谋 抓取 访客数据 JS版/谷歌插件版
    EF 多表关联
    个人 圈外同学 对比分析
  • 原文地址:https://www.cnblogs.com/jiaoran/p/14345755.html
Copyright © 2011-2022 走看看