热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

php缓存文件技术介绍-PHP源码

下面总结了三种缓存文件方法,一种是nginx下的缓存fastcgi_cache和proxy_cache,一种利用memcache缓存,另一种是利用php文件缓存哦。
下面总结了三种缓存文件方法,一种是nginx下的缓存fastcgi_cache和proxy_cache,一种利用memcache缓存,另一种是利用php文件缓存哦。

nginx有两种缓存机制:fastcgi_cache和proxy_cache
下面我们来说说这两种缓存机制的区别吧
proxy_cache作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态的
fastcgi_cache作用是缓存fastcgi生成的内容,很多情况是php生成的动态内容
proxy_cache缓存减少了nginx与后端通信的次数,节省了传输时间和后端带宽
fastcgi_cache缓存减少了nginx与php的通信次数,更减轻了php和数据库的压力。

proxy_cache缓存设置
#注:proxy_temp_path和proxy_cache_path指定的路径必须在同一分区
proxy_temp_path /data0/proxy_temp_dir;
#设置Web缓存区名称为cache_one,内存缓存空间大小为200MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。
proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zOne=cache_one:200m inactive=1d max_size=30g;

代码如下

server
{
listen 80;
server_name www.yourdomain.com 192.168.8.42;
index index.html index.htm;
root /data0/htdocs/www;

location /
{
#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_one;
#对不同的HTTP状态码设置不同的缓存时间
proxy_cache_valid 200 304 12h;
#以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://backend_server;
expires 1d;
}

#用于清除缓存,假设一个URL为http://192.168.8.42/test.txt,通过访问http://192.168.8.42/purge/test.txt就可以清除该URL的缓存。
location ~ /purge(/.*)
{
#设置只允许指定的IP或IP段才可以清除URL缓存。
allow 127.0.0.1;
allow 192.168.0.0/16;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}

#扩展名以.php、.jsp、.cgi结尾的动态应用程序不缓存。
location ~ .*.(php|jsp|cgi)?$
{
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://backend_server;
}

access_log off;
}
}


fastcgi_cache缓存设置
#定义缓存存放的文件夹

代码如下
fastcgi_cache_path /tt/cache levels=1:2 keys_zOne=NAME:2880m inactive=2d max_size=10G;

#定义缓存不同的url请求

代码如下
fastcgi_cache_key "$scheme$request_method$host$uri$arg_filename$arg_x$arg_y";

server {
listen 8080;
server_name www.example .com;
location / {
root /www;
index index.html index.htm index.php;
}

location ~ (|.php)$ {
root /www;
fastcgi_pass 127.0.0.1:9000;

fastcgi_cache NAME;
fastcgi_cache_valid 200 48h;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;

fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi.conf;
#设置缓存的过程中发现无法获取COOKIE,经查需要定义这句话
fastcgi_pass_header Set-COOKIE;
}

log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
access_log /httplogs/access.log access;
}

总的来说 nginx的proxy_cache和fastcgi_cache的缓存配置差不多。

--------------------------------------------------------------------------------

memcache缓存
在讨论memcache缓存之前,我们先了解下mysql的内存缓存吧
mysql的内存缓存可以在my.cnf中指定大小:内存表和临时表不同,临时表也是存放内存中,临时表最大的内存需要通过tmp_table_size=128M设定。当数据查过临时表的最大值设定时,自动转为磁盘表,此时因需要进行IO操作,性能会大大下降,而内存表不会,内存满了后,会提示数据满错误。
例:

代码如下
create table test
(
id int unsigned not null auto_increment primary key
state char(10),
type char(20),
date char(30)
)engine=memory default charset=utf8

内存表的特性:
1.内存表的表定义存放在磁盘上,扩展名为.frm,所以重启不会丢失
2.内存表的数据是存放在内存中,重启会丢失数据
3.内存表使用一个固定的长度格式
4.内存表不支持blob或text列,比如varchar与text字段就不会被支持
5.内存表支持auto_increment列和对可包含null值的列的索引
6.内存表不支持事物
7.内存表是表锁,当修改频繁时,性能可能会下降

分享一个存php缓存类

代码如下

class Cache
{

private static $_instance;
protected $_cacheId = null;

const CLEANING_MODE_ALL = 'all';
const CLEANING_MODE_OLD = 'old';

protected $_optiOns= array(
'cache_dir' => null, //数据缓存目录
'life_time' => 7200, //缓存时间
'page_dir' => null, //文本缓存目录
'cache_prefix' => 'cache_' //缓存前缀
);

private function __construct(){}

//创建__clone方法防止对象被复制克隆
private function __clone(){}

/**
* 取缓存对象,如果存在直接返回,如果不存在实例化本身
* @return object cache
*/
public static function getInstance(){

if(! self::$_instance){

self::$_instance = new self();
}

return self::$_instance;
}

/**
* 设置缓存参数集
* @param array $options 要设置的缓存参数集
*/
public function setOptions($optiOns= array()){

while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
}

/**
* 取得当前缓存参数,如果$name为空返回全部参数,否则返回该参数值
* @param string $name 要返回的参数名称
* @return string or array $option;
*/
public function getOption($name = null){

if(null === $name)
return $this->_options;

if (!is_string($name)) {
throwException("不正确的参数名称 : $name");
}

if (array_key_exists($name, $this->_options)){
return $this->_options[$name];
}
}

/**
* 设置缓存参数
* @param array $options 要设置的缓存参数
*/
protected function setOption($name, $value){

if (!is_string($name)) {
throwException("不正确的参数名称 : $name");
}
$name = strtolower($name);
if (array_key_exists($name, $this->getOption())){
$this->_options[$name] = $value;
}

if ($this->_options['cache_dir'] === null) {
$this->setOption('cache_dir', $this->getTmpDir() . DIRECTORY_SEPARATOR);
}

if ($this->_options['page_dir'] === null) {
$this->setOption('page_dir', $this->getTmpDir() . DIRECTORY_SEPARATOR);
}
}

/**
* 读取数据缓存,如果不存在或过期,返回false
* @param string $id 缓存ID
* @return false or data
*/
public function load($id){

$this->_cacheId = $id;
$file = $this->getOption('cache_dir') . $this->getOption('cache_prefix') . $this->_cacheId;

if (@filemtime($file) >= time()){

return unserialize(file_get_contents($file));
} else {
@unlink($file);
return false;
}
}

/**
* 保存数据缓存,并设置缓存过期时间
* @param array or string $data 要缓存的数据
* @param int $lifeTime 缓存过期时间
*/
public function save($data, $lifeTime = null){

if(null !== $lifeTime)
$this->setOption('life_time', $lifeTime);

$file = $this->getOption('cache_dir') . $this->getOption('cache_prefix') . $this->_cacheId;
$data = serialize($data);
@file_put_contents($file, $data);
@chmod($file, 0777);
@touch($file, time() + $this->getOption('life_time']));
}

/**
* 读取输出缓存,如果不存在或缓存过期将重新开启输出缓存
* @param string $id 缓存ID
*/
public function start($id){

$this->_cacheId = $id;
$file = $this->getOption('page_dir') . $this->getOption('cache_prefix') . $this->_cacheId;

if (@filemtime($file) >= time()){

return file_get_contents($file);
} else {
@unlink($file);
ob_start();
return false;
}
}

/**
* 删除指定ID缓存
* @param string $id 缓存ID
*/
public function remove($id){

$this->_cacheId = $id;
//删除附合条件的数据缓存
$file = $this->getOption('cache_dir') . $this->getOption('cache_prefix') . $this->_cacheId;
@unlink($file);
//删除附合条件的输出缓存
$file = $this->getOption('page_dir') . $this->getOption('cache_prefix') . $this->_cacheId;
@unlink($file);
}

/**
* 保存输出缓存,并设置缓存过期时间
* @param int $lifeTime 缓存过期时间
*/
public function end($lifeTime = null){

if(null !== $lifeTime)
$this->setOption('life_time', $lifeTime);

$file = $this->getOption('page_dir') . $this->getOption('cache_prefix') . $this->_cacheId;
$data = ob_get_contents();
ob_end_clean();
@file_put_contents($file, $data);
@chmod($file, 0777);
@touch($file, time() + $this->getOption('life_time']));
}

/**
* 根据参数清除相应缓存
* @param string $mode 缓存类型,包括(CLEANING_MODE_ALL:所有缓存, CLEANING_MODE_OLD: 过期缓存)
*/
public function clear($mode = CLEANING_MODE_OLD){

$dirs = array('cache_dir', 'page_dir');
foreach($dirs as $value){
if(null != $this->getOption($value)){
$files = scandir($this->getOption($value));
switch ($mode) {

case CLEANING_MODE_ALL:
default:
foreach ($files as $val){
@unlink($this->getOption($value) . $val);
}
break;

case CLEANING_MODE_OLD:
default:
foreach ($files as $val){
if (filemtime($this->getOption($value) . $val) @unlink($this->getOption($value) . $val);
}
}
break;
}
}
}
}

/**
* 取临时文件夹为缓存文件夹
* @return $dir 临时文件夹路径
*/
public function getTmpDir(){

$tmpdir = array();
foreach (array($_ENV, $_SERVER) as $tab) {
foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
if (isset($tab[$key])) {
if (($key == 'windir') or ($key == 'SystemRoot')) {
$dir = realpath($tab[$key] . '\temp');
} else {
$dir = realpath($tab[$key]);
}
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
}
}
$upload = ini_get('upload_tmp_dir');
if ($upload) {
$dir = realpath($upload);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if (function_exists('sys_get_temp_dir')) {
$dir = sys_get_temp_dir();
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
//通过尝试创建一个临时文件来检测
$tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
if ($tempFile) {
$dir = realpath(dirname($tempFile));
unlink($tempFile);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if ($this->_isGoodTmpDir('/tmp')) {
return '/tmp';
}
if ($this->_isGoodTmpDir('\temp')) {
return '\temp';
}
throw new Exception('无法确定临时目录,请手动指定cache_dir', E_USER_ERROR);
}

/**
* 验证给定的临时目录是可读和可写的
*
* @param string $dir 临时文件夹路径
* @return boolean true or false 临时文件夹路径是否可读写
*/
protected function _isGoodTmpDir($dir){

if (is_readable($dir)) {
if (is_writable($dir)) {
return true;
}
}
return false;
}


}//endclass


推荐阅读
  • 构建LNMP架构平台
    LNMP架构的组成:Linux、Nginx、MySQL、PHP关于NginxNginx与apache的作用一样,都是为了搭建网站服务器,由俄罗斯人lgorsysoev开发,其特点是 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • LVS实现负载均衡的原理LVS负载均衡负载均衡集群是LoadBalance集群。是一种将网络上的访问流量分布于各个节点,以降低服务器压力,更好的向客户端 ... [详细]
  • 目录浏览漏洞与目录遍历漏洞的危害及修复方法
    本文讨论了目录浏览漏洞与目录遍历漏洞的危害,包括网站结构暴露、隐秘文件访问等。同时介绍了检测方法,如使用漏洞扫描器和搜索关键词。最后提供了针对常见中间件的修复方式,包括关闭目录浏览功能。对于保护网站安全具有一定的参考价值。 ... [详细]
  • 负载均衡_Nginx反向代理动静分离负载均衡及rewrite隐藏路径详解(Nginx Apache MySQL Redis)–第二部分
    nginx反向代理、动静分离、负载均衡及rewrite隐藏路径详解 ... [详细]
  • Linux下部署Symfoy2对app/cache和app/logs目录的权限设置,symfoy2logs
    php教程|php手册xml文件php教程-php手册Linux下部署Symfoy2对appcache和applogs目录的权限设置,symfoy2logs黑色记事本源码,vsco ... [详细]
  • Nginx Buffer 机制引发的下载故障
    Nginx ... [详细]
  • Linux一键安装web环境全攻略
    摘自阿里云服务器官网,此处一键安装包下载:点此下载安装须知1、此安装包可在阿里云所有Linux系统上部署安装,此安装包包含的软件及版本为& ... [详细]
  • LVS-DR直接路由实现负载均衡示例
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • Nginx使用AWStats日志分析的步骤及注意事项
    本文介绍了在Centos7操作系统上使用Nginx和AWStats进行日志分析的步骤和注意事项。通过AWStats可以统计网站的访问量、IP地址、操作系统、浏览器等信息,并提供精确到每月、每日、每小时的数据。在部署AWStats之前需要确认服务器上已经安装了Perl环境,并进行DNS解析。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • k8s+springboot+Eureka如何平滑上下线服务
    k8s+springboot+Eureka如何平滑上下线服务目录服务平滑上下线-k8s版本目录“上篇介绍了springboot+Euraka服务平滑上下线的方式,有部分小伙伴反馈k ... [详细]
  • 抖音服务器带宽有多大,才能供上亿人同时刷?
    最近看到一个有意思的提问:抖音服务器带宽有多大,为什么能够供那么多人同时刷?今天来给大家科普一下。 ... [详细]
  • 域名解析系统DNS
    文章目录前言一、域名系统概述二、因特网的域名结构三、域名服务器1.根域名服务器2.顶级域名服务器(TLD,top-leveldomain)3.权威(Authoritative)域名 ... [详细]
author-avatar
遗忘的花心本分尐男人
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有