php 缓存工具类 实现网页缓存
php 缓存工具类 实现网页缓存
php程序在抵抗大流量访问的时候动态网站往往都是难以招架,所以要引入缓存机制,一般情况下有两种类型缓存
一、文件缓存
二、数据查询结果缓存,使用内存来实现高速缓存
本例主要使用文件缓存。
主要原理使用缓存函数来存储网页显示结果,如果在规定时间里再次调用则可以加载缓存文件。
工具类代码:
// 文件缓存类
class Cache {
/**
* $dir : 缓存文件存放目录
* $lifetime : 缓存文件有效期,单位为秒
* $cacheid : 缓存文件路径,包含文件名
* $ext : 缓存文件扩展名(可以不用),这里使用是为了查看文件方便
*/
private $dir;
private $lifetime;
private $cacheid;
private $ext;
/**
* 析构函数,检查缓存目录是否有效,默认赋值
*/
function __construct($dir = '', $lifetime = 1800) {
if ($this->dir_isvalid ( $dir )) {
$this->dir = $dir;
$this->lifetime = $lifetime;
$this->ext = '.Php';
$this->cacheid = $this->getcacheid ();
}
}
/**
* 检查缓存是否有效
*/
private function isvalid() {
if (! file_exists ( $this->cacheid ))
return false;
if (! (@$mtime = filemtime ( $this->cacheid )))
return false;
if (mktime () - $mtime > $this->lifetime)
return false;
return true;
}
/**
* 写入缓存
* $mode == 0 , 以浏览器缓存的方式取得页面内容
* $mode == 1 , 以直接赋值(通过$content参数接收)的方式取得页面内容
* $mode == 2 , 以本地读取(fopen ile_get_contents)的方式取得页面内容(似乎这种方式没什么必要)
*/
public function write($mode = 0, $content = '') {
switch ($mode) {
case 0 :
$content = ob_get_contents ();
break;
default :
break;
}
ob_end_flush ();
try {
file_put_contents ( $this->cacheid, $content );
} catch ( Exception $e ) {
$this->error ( '写入缓存失败!请检查目录权限!' );
}
}
/**
* 加载缓存
* exit() 载入缓存后终止原页面程序的执行,缓存无效则运行原页面程序生成缓存
* ob_start() 开启浏览器缓存用于在页面结尾处取得页面内容
*/
public function load() {
if ($this->isvalid ()) {
// 以下两种方式,哪种方式好?????
require_once ($this->cacheid);
echo "<!--缓存-->";
// echo file_get_contents($this->cacheid);
exit ();
} else {
ob_start ();
}
}
/**
* 清除缓存
*/
public function clean() {
try {
unlink ( $this->cacheid );
} catch ( Exception $e ) {
$this->error ( '清除缓存文件失败!请检查目录权限!' );
}
}
/**
* 取得缓存文件路径
*/
private function getcacheid() {
return $this->dir . md5 ( $this->geturl () ) . $this->ext;
}
/**
* 检查目录是否存在或是否可创建
*/
private function dir_isvalid($dir) {
if (is_dir ( $dir ))
return true;
try {
mkdir ( $dir, 0777 );
} catch ( Exception $e ) {
$this->error ( '所设定缓存目录不存在并且创建失败!请检查目录权限!' );
return false;
}
return true;
}
/**
* 取得当前页面完整url
*/
private function geturl() {
$url = '';
if (isset ( $_SERVER ['REQUEST_URI'] )) {
$url = $_SERVER ['REQUEST_URI'];
} else {
$url = $_SERVER ['Php_SELF'];
$url .= empty ( $_SERVER ['QUERY_STRING'] ) ? '' : '?' . $_SERVER ['QUERY_STRING'];
}
return $url;
}
/**
* 输出错误信息
*/
private function error($str) {
echo '<div style="color:red;">' . $str . '</div>';
}
}
使用方法:
使用方法如下:
一部分代码放在要被缓存逻辑代码前面:
$cachedir = './Cache/'; // 设定缓存目录
$cache = new Cache ( $cachedir, 33 ); // 省略参数即采用缺省设置, $cache = new Cache($cachedir);
if (@$_GET ['cacheact'] != 'rewrite' || @$_GET ['clearCache'] == 'ok') // 此处为一技巧,通过xx.Php?cacheact=rewrite更新缓存,以此类推,还可以设定一些其它操作
$cache->load (); // 装载缓存,缓存有效则不执行以下页面代码
// 页面代码开始
一部分放在被缓存逻辑代码后面:
// 页面代码结束
$cache->write (); // 首次运行或缓存过期,生成缓存
原文地址:http://sijienet.com/bbs/?leibie=showinfo&id=50
php 缓存工具类 实现网页缓存的更多相关文章
- Cache【硬盘缓存工具类(包含内存缓存LruCache和磁盘缓存DiskLruCache)】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 内存缓存LruCache和磁盘缓存DiskLruCache的封装类,主要用于图片缓存. 效果图 代码分析 内存缓存LruCache和 ...
- 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...
- Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
Go/Python/Erlang编程语言对比分析及示例 本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...
- redis缓存工具类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis ...
- redis缓存工具类,提供序列化接口
1.序列化工具类 package com.qicheshetuan.backend.util; import java.io.ByteArrayInputStream; import java.io. ...
- SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码
创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...
- CookieUtils-浏览器缓存工具类
package cn.yonyong.myproject.commons.utils; import javax.servlet.http.Cookie; import javax.servlet.h ...
- 缓存工具类CacheHelper
代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...
- 基于spring的redisTemplate的缓存工具类
pom.xml文件添加 <!-- config redis data and client jar --><dependency> <groupId>org.spr ...
随机推荐
- 初探linux子系统集之led子系统(三)【转】
本文转载自:http://blog.csdn.net/eastmoon502136/article/details/37822837 世界杯结束了,德国战车夺得了大力神杯,阿根廷最终还是失败了.也许3 ...
- 获取cookie值
function get_cookie(Name) { var search = Name + "=" var returnvalue = ""; if (do ...
- BZOJ_4311_向量_线段树按时间分治
BZOJ_4311_向量_CDQ分治+线段树按时间分治 Description 你要维护一个向量集合,支持以下操作: 1.插入一个向量(x,y) 2.删除插入的第i个向量 3.查询当前集合与(x,y) ...
- 喵哈哈村的魔法考试 Round #1 (Div.2)
比赛地址:http://qscoj.cn/contest/2/ 都是中文题,这里不在详述题意 A.喵哈哈村的魔法石 分析:暴力求解 #include<iostream> #include& ...
- 读取每行的数据,加入到list中
有txt文件中,每行都有一个字符串或者数据,将每行的数据转换到一个list中 例如: 1 2 3 6 实现: f = open("test1.txt",'r') list1 = [ ...
- B. Mishka and trip
time limit per test 1 second memory limit per test 256 megabytes input standard input output standar ...
- linux中fork对打开文件的处理
1 子进程复制父进程的数据段.BBS段.代码段.堆空间.栈空间和文件描述符 2 对于文件描述符采用共享的方式 后面这个例子可以清晰的看出 #include <sys/types.h> #i ...
- c++中.c_str和.c_data
1 关于.c_str的用法: const char *c_str(); 这个数组的数据是临时的,当有一个改变这些数据的成员函数被调用后,其中的数据就会失效.因此要么现用先转换,要么把它的数据复制到用户 ...
- Epoll简介以及例子
第一部分:Epoll简介 问题 : Select,Poll和Epoll的区别 答案 : Epoll和Select的区别 1. 遍历方式的区别.select判断是否有事件发生是遍历的,而epoll是事 ...
- E20180420-hm
prior adj. 优先的; 占先的; 在…之前 alignment n. 结盟; 队列,排成直线; 校直,调整; [工] 准线; align vt. 使成一线,使结盟; 排整齐 vi. 排 ...