实例介绍
【实例简介】
thnkphp5行为扩展html静态缓存
利用钩子thinkphp钩子进行行为扩展。先上本地测试结果
关闭缓存:
[email protected] */" _ue_custom_node_="true">:/home/www/wwwroot/yunshare.qq$ ab -n1000 -c10 http://yunshare.qq/Article/8/9.html This is ApacheBench, Version 2.3 Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking yunshare.qq (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests Completed 1000 requests Finished 1000 requests Server Software: nginx/1.10.0 Server Hostname: yunshare.qq Server Port: 80 Document Path: /Article/8/9.html Document Length: 67926 bytes Concurrency Level: 10 Time taken for tests: 66.869 seconds Complete requests: 1000 Failed requests: 0 Total transferred: 68095000 bytes HTML transferred: 67926000 bytes Requests per second: 14.95 [#/sec] (mean) Time per request: 668.692 [ms] (mean) Time per request: 66.869 [ms] (mean, across all concurrent requests) Transfer rate: 994.46 [Kbytes/sec] received Connection Times (ms) min mean[ /-sd] median max Connect: 0 0 0.2 0 3 Processing: 252 666 72.9 661 1066 Waiting: 252 664 72.5 659 1065 Total: 255 666 72.9 661 1066 Percentage of the requests served within a certain time (ms) 50% 661 66% 687 75% 704 80% 716 90% 757 95% 792 98% 834 99% 858 100% 1066 (longest request)
开启缓存:
[email protected] */" _ue_custom_node_="true">:/home/www/wwwroot/yunshare.qq$ ab -n1000 -c10 http://yunshare.qq/Article/8/9.html This is ApacheBench, Version 2.3 Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking yunshare.qq (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests Completed 1000 requests Finished 1000 requests Server Software: nginx/1.10.0 Server Hostname: yunshare.qq Server Port: 80 Document Path: /Article/8/9.html Document Length: 44835 bytes Concurrency Level: 10 Time taken for tests: 20.578 seconds Complete requests: 1000 Failed requests: 0 Total transferred: 45004000 bytes HTML transferred: 44835000 bytes Requests per second: 48.60 [#/sec] (mean) Time per request: 205.777 [ms] (mean) Time per request: 20.578 [ms] (mean, across all concurrent requests) Transfer rate: 2135.77 [Kbytes/sec] received Connection Times (ms) min mean[ /-sd] median max Connect: 0 0 0.1 0 2 Processing: 69 205 30.7 202 344 Waiting: 68 202 30.3 200 340 Total: 71 205 30.6 202 344 Percentage of the requests served within a certain time (ms) 50% 202 66% 213 75% 220 80% 224 90% 239 95% 254 98% 286 99% 328 100% 344 (longest request)
使用方法(和thinkphp3.2相似)
'配置值' 'html_cache_on' => false, // 开启静态缓存 'html_cache_time' => 7200, // 全局静态缓存有效期(秒) 'html_file_suffix' => '.shtml', // 设置静态缓存文件后缀 'html_cache_compile_type' => 'file',//缓存存储驱动 'html_cache_rules' => array( // 定义静态缓存规则 // // 定义格式1 数组方式 //'静态地址' => array('静态规则', '有效期', '附加规则'), //1.任意控制器的任意操作都适用 '*'=>array('{$_SERVER.REQUEST_URI|md5}'), //2.任意控制器的md5操作 'md5'=>array('{:module}/{:controller}/{:action}_{id|md5}'), //3.Static控制器的所有操作 'Static:'=>array('{:module}/{:controller}/{:action}',50)//第一个参数是构造的字符串,后面是缓存50秒 //4.Hmtl控制器的md5操作 'Html:md5'=>array('{:module}/{:controller}/{:action}'), ) );
参考:http://wp.iyouths.org/250.html
扩展步骤
-
文件位置:appplication/tags.php(或appplication/index/tags.php)
[ 'app\\index\\behavior\\ReadHtmlCacheBehavior',//可自行修改文件位置 ], 'view_filter' => [ 'app\\index\\behavior\\WriteHtmlCacheBehavior', ], ];
-
添加文件
application/index/behavior/ReadHtmlCacheBehavior.php
application/index/behavior/WriteHtmlCacheBehavior.php
注意:
检查是否修改模板文件改为了app_debug = true
【核心代码】
<?php namespace app\index\behavior; /** * 系统行为扩展:静态缓存读取 */ class ReadHtmlCacheBehavior { protected static $actionName; protected static $controllerName; protected static $moduleName; protected $storage; // 行为扩展的执行入口必须是run public function run(&$params){ self::$actionName = request()->action(); self::$controllerName = request()->controller(); self::$moduleName = request()->module(); // 开启静态缓存 if('GET' === request()->method() && config('html_cache_on')) { $cacheTime = $this->requireHtmlCache(); if( false !== $cacheTime && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { //静态页面有效 // 读取静态页面输出 include HTML_FILE_NAME; exit(); } } } // 判断是否需要静态缓存 static private function requireHtmlCache() { // 分析当前的静态规则 $htmls = config('html_cache_rules'); // 读取静态规则 if(!empty($htmls)) { $htmls = array_change_key_case($htmls); // 静态规则文件定义格式 actionName=>array('静态规则','缓存时间','附加规则') // 'read'=>array('{id},{name}',60,'md5') 必须保证静态规则的唯一性 和 可判断性 // 检测静态规则 $controllerName = (strtolower(self::$controllerName)); $actionName = strtolower(self::$actionName); if(isset($htmls[$controllerName.':'.$actionName])) { $html = $htmls[$controllerName.':'.$actionName]; // 某个控制器的操作的静态规则 }elseif(isset($htmls[$controllerName.':'])){// 某个控制器的静态规则 $html = $htmls[$controllerName.':']; }elseif(isset($htmls[$actionName])){ $html = $htmls[$actionName]; // 所有操作的静态规则 }elseif(isset($htmls['*'])){ $html = $htmls['*']; // 全局静态规则 } if(!empty($html)) { // thinkphp5 $method = request()->method(); switch ($method) { case 'GET': $_GET = request()->param(); break; case 'POST': $_POST = request()->param(); break; case 'REQUEST': $_REQUEST = request()->param(); break; case 'SERVER': $_SERVER = request()->param(); break; case 'SESSION': $_SESSION = request()->param(); break; case 'COOKIE': $_COOKIE = request()->param(); break; default: break; } // 解读静态规则 $rule = is_array($html)?$html[0]:$html; // 以$_开头的系统变量 $callback = function($match){ switch($match[1]){ case '_GET': $var = $_GET[$match[2]]; break; case '_POST': $var = $_POST[$match[2]]; break; case '_REQUEST': $var = $_REQUEST[$match[2]]; break; case '_SERVER': $var = $_SERVER[$match[2]]; break; case '_SESSION': $var = $_SESSION[$match[2]]; break; case '_COOKIE': $var = $_COOKIE[$match[2]]; break; } return (count($match) == 4) ? $match[3]($var) : $var; }; $rule = preg_replace_callback('/{\$(_\w )\.(\w )(?:\|(\w ))?}/', $callback, $rule); // {ID|FUN} GET变量的简写 $rule = preg_replace_callback('/{(\w )\|(\w )}/', function($match){return $match[2]($_GET[$match[1]]);}, $rule); $rule = preg_replace_callback('/{(\w )}/', function($match){return $_GET[$match[1]];}, $rule); // 特殊系统变量 $rule = str_ireplace( array('{:controller}','{:action}','{:module}'), array(self::$controllerName,self::$actionName,self::$moduleName), $rule); // {|FUN} 单独使用函数 $rule = preg_replace_callback('/{|(\w )}/', function($match){return $match[1]();},$rule); // $cacheTime = config('html_cache_time') ?? '.html';//php7 $cacheTime = config('html_cache_time'); $cacheTime = $cacheTime ? $cacheTime: 60; if(is_array($html)){ if(!empty($html[2])) $rule = $html[2]($rule); // 应用附加函数 $cacheTime = isset($html[1])?$html[1]:$cacheTime; // 缓存有效期 }else{ $cacheTime = $cacheTime; } // 当前缓存文件 // $html_file_suffix = config('html_file_suffix') ?? '.html';//php7 $html_file_suffix = config('html_file_suffix'); $html_file_suffix = $html_file_suffix ? $html_file_suffix: '.html'; define('HTML_FILE_NAME',RUNTIME_PATH . $rule.$html_file_suffix); return $cacheTime; } } // 无需缓存 return false; } /** * 检查静态HTML文件是否有效 * 如果无效需要重新更新 * @access public * @param string $cacheFile 静态文件名 * @param integer $cacheTime 缓存有效期 * @return boolean */ static public function checkHTMLCache($cacheFile='',$cacheTime='') { if (true == config('app_debug')) { return false; } elseif (!is_file($cacheFile)) { return false; // }elseif (filemtime(\think\view()->parseTemplate()) > $this->storage()->read($cacheFile,'mtime')) { // // 模板文件如果更新静态文件需要更新 // return false; } elseif (!is_numeric($cacheTime) && function_exists($cacheTime)){ return $cacheTime($cacheFile); } elseif ($cacheTime != 0 && time() > filemtime($cacheFile) $cacheTime) { // 文件是否在有效期 return false; } //静态文件有效 return true; } }
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论