网站地图    收藏   

主页 > php专栏 > 流程控制语句 >

php缓存文件技术介绍 - php会话

来源:自学PHP网    时间:2014-11-27 22:01 作者: 阅读:

[导读] 下面总结了三种缓存文件方法,一种是nginx下的缓存fastcgi_cache和proxy_cache,一种利用memcache缓存,另一种是利用php文件缓存 nginx有两种缓存机制:fastcgi_cache和proxy_cache下面我们来说说这两...

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;

实例代码如下:

  1. server 
  2.   { 
  3.     listen       80; 
  4.     server_name  www.phpfensi.com 192.168.8.42; 
  5.     index index.html index.htm; 
  6.     root  /data0/htdocs/www;  
  7.  
  8.     location / 
  9.     { 
  10.          #如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。 
  11.          proxy_next_upstream http_502 http_504 error timeout invalid_header; 
  12.          proxy_cache cache_one; 
  13.          #对不同的HTTP状态码设置不同的缓存时间 
  14.          proxy_cache_valid  200 304 12h; 
  15.          #以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内 
  16.          proxy_cache_key $host$uri$is_args$args
  17.          proxy_set_header Host  $host
  18.          proxy_set_header X-Forwarded-For  $remote_addr
  19.          proxy_pass http://backend_server; 
  20.          expires      1d; 
  21.     } 
  22.      
  23.     #用于清除缓存,假设一个URL为http://192.168.8.42/test.txt,通过访问http://192.168.8.42/purge/test.txt就可以清除该URL的缓存。 
  24.     location ~ /purge(/.*) 
  25.     { 
  26.      #设置只允许指定的IP或IP段才可以清除URL缓存。 
  27.      allow            127.0.0.1; 
  28.      allow            192.168.0.0/16; 
  29.      deny            all; 
  30.      proxy_cache_purge    cache_one   $host$1$is_args$args
  31.     }    
  32.  
  33.     #扩展名以.php、.jsp、.cgi结尾的动态应用程序不缓存。 
  34.     location ~ .*.(php|jsp|cgi)?$ 
  35.     { 
  36.          proxy_set_header Host  $host
  37.          proxy_set_header X-Forwarded-For  $remote_addr
  38.          proxy_pass http://backend_server; 
  39.     } 
  40.  
  41.     access_log  off; 
  42.   } 

fastcgi_cache缓存设置

#定义缓存存放的文件夹,代码如下:

fastcgi_cache_path   /tt/cache  levels=1:2 keys_zone=NAME:2880m inactive=2d max_size=10G;

#定义缓存不同的url请求,代码如下:

  1. fastcgi_cache_key "$scheme$request_method$host$uri$arg_filename$arg_x$arg_y"
  2.  
  3. server { 
  4.         listen       8080; 
  5.         server_name  www.example .com; 
  6.         location / { 
  7.             root   /www; 
  8.             index  index.html index.htm index.php; 
  9.         } 
  10.  
  11.         location ~ (|.php)$ { 
  12.             root           /www; 
  13.             fastcgi_pass   127.0.0.1:9000; 
  14.              
  15.             fastcgi_cache   NAME; 
  16.             fastcgi_cache_valid 200 48h; 
  17.             fastcgi_cache_min_uses  1; 
  18.             fastcgi_cache_use_stale error  timeout invalid_header http_500; 
  19.              
  20.             fastcgi_index  index.php; 
  21.             fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name; 
  22.             include        fastcgi.conf; 
  23.             #设置缓存的过程中发现无法获取cookie,经查需要定义这句话 
  24.             fastcgi_pass_header Set-Cookie; 
  25.         } 
  26.  
  27.         log_format  access  '$remote_addr - $remote_user [$time_local] "$request" ' 
  28.               '$status $body_bytes_sent "$http_referer" ' 
  29.               '"$http_user_agent" $http_x_forwarded_for'
  30. access_log  /httplogs/access.log  access; 

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

memcache缓存

在讨论memcache缓存之前,我们先了解下mysql的内存缓存吧.

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

  1. create table test 
  2.     id int unsigned not null auto_increment primary key 
  3.     state char(10), 
  4.     type char(20), 
  5.     date char(30) 
  6. )engine=memory default charset=utf8 

内存表的特性:

1.内存表的表定义存放在磁盘上,扩展名为.frm,所以重启不会丢失

2.内存表的数据是存放在内存中,重启会丢失数据

3.内存表使用一个固定的长度格式

4.内存表不支持blob或text列,比如varchar与text字段就不会被支持

5.内存表支持auto_increment列和对可包含null值的列的索引

6.内存表不支持事物

7.内存表是表锁,当修改频繁时,性能可能会下降

分享一个存php缓存类,代码如下:

  1. <?php 
  2.  
  3. class Cache 
  4.  
  5.     private static $_instance
  6.     protected $_cacheId = null; 
  7.  
  8.     const CLEANING_MODE_ALL  = 'all'
  9.     const CLEANING_MODE_OLD = 'old'
  10.  
  11.     protected $_options = array
  12.         'cache_dir' => null,                  //数据缓存目录 
  13.         'life_time' => 7200,                  //缓存时间 
  14.         'page_dir' => null,                   //文本缓存目录 
  15.         'cache_prefix' => 'cache_'        //缓存前缀 
  16.     ); 
  17.  
  18.     private function __construct(){} 
  19.     
  20.     //创建__clone方法防止对象被复制克隆 
  21.     private function __clone(){} 
  22.     
  23.     /** 
  24.      * 取缓存对象,如果存在直接返回,如果不存在实例化本身 
  25.      * @return object cache 
  26.      */ 
  27.     public static function getInstance(){ 
  28.         
  29.         if(! self::$_instance){ 
  30.         
  31.             self::$_instance = new self(); 
  32.         } 
  33.         
  34.         return self::$_instance
  35.     } 
  36.         
  37.     /** 
  38.      * 设置缓存参数集 
  39.      * @param array $options 要设置的缓存参数集 
  40.      */ 
  41.     public function setOptions($options = array()){ 
  42.     
  43.         while (list($name$value) = each($options)) { 
  44.             $this->setOption($name$value); 
  45.         } 
  46.     } 
  47.     
  48.     /** 
  49.      * 取得当前缓存参数,如果$name为空返回全部参数,否则返回该参数值 
  50.      * @param string $name 要返回的参数名称 
  51.      * @return string or array $option; 
  52.      */ 
  53.     public function getOption($name = null){ 
  54.     
  55.         if(null === $name
  56.             return $this->_options; 
  57.     
  58.         if (!is_string($name)) { 
  59.             throwException("不正确的参数名称 : $name"); 
  60.         } 
  61.         
  62.         if (array_key_exists($name$this->_options)){ 
  63.             return $this->_options[$name]; 
  64.         } 
  65.     } 
  66.     
  67.     /** 
  68.      * 设置缓存参数 
  69.      * @param array $options 要设置的缓存参数 
  70.      */ 
  71.     protected function setOption($name$value){ 
  72.     
  73.         if (!is_string($name)) { 
  74.             throwException("不正确的参数名称 : $name"); 
  75.         } 
  76.         $name = strtolower($name); 
  77.         if (array_key_exists($name$this->getOption())){ 
  78.             $this->_options[$name] = $value
  79.         } 
  80.         
  81.         if ($this->_options['cache_dir'] === null) { 
  82.             $this->setOption('cache_dir'$this->getTmpDir() . DIRECTORY_SEPARATOR); 
  83.         } 
  84.         
  85.         if ($this->_options['page_dir'] === null) { 
  86.             $this->setOption('page_dir'$this->getTmpDir() . DIRECTORY_SEPARATOR); 
  87.         } 
  88.     } 
  89.     
  90.     /** 
  91.      * 读取数据缓存,如果不存在或过期,返回false 
  92.      * @param string $id 缓存ID 
  93.      * @return false or data 
  94.      */ 
  95.     public function load($id){ 
  96.  
  97.         $this->_cacheId = $id;        
  98.         $file = $this->getOption('cache_dir') . $this->getOption('cache_prefix') . $this->_cacheId; 
  99.                 
  100.         if (@filemtime($file) >= time()){ 
  101.         
  102.             return unserialize(file_get_contents($file));  
  103.         } else { 
  104.             @unlink($file); 
  105.             return false; 
  106.         } 
  107.     } 
  108.     
  109.     /** 
  110.      * 保存数据缓存,并设置缓存过期时间 
  111.      * @param array or string $data 要缓存的数据 
  112.      * @param int $lifeTime 缓存过期时间 
  113.      */ 
  114.     public function save($data$lifeTime = null){ 
  115.     
  116.         if(null !== $lifeTime
  117.             $this->setOption('life_time'$lifeTime); 
  118.     
  119.         $file = $this->getOption('cache_dir') . $this->getOption('cache_prefix') . $this->_cacheId; 
  120.         $data = serialize($data); 
  121.         @file_put_contents($file$data); 
  122.         @chmod($file, 0777); 
  123.         @touch($file, time() + $this->getOption('life_time'])); 
  124.     }    
  125.     
  126.     /** 
  127.      * 读取输出缓存,如果不存在或缓存过期将重新开启输出缓存 
  128.      * @param string $id 缓存ID 
  129.      */ 
  130.     public function start($id){ 
  131.  
  132.         $this->_cacheId = $id
  133.         $file = $this->getOption('page_dir') . $this->getOption('cache_prefix') . $this->_cacheId; 
  134.                 
  135.         if (@filemtime($file) >= time()){ 
  136.         
  137.             return file_get_contents($file); 
  138.         } else { 
  139.             @unlink($file); 
  140.             ob_start(); 
  141.             return false; 
  142.         } 
  143.     } 
  144.  
  145.     /** 
  146.      * 删除指定ID缓存 
  147.      * @param string $id 缓存ID 
  148.      */ 
  149.     public function remove($id){ 
  150.  
  151.         $this->_cacheId = $id
  152.         //删除附合条件的数据缓存 
  153.         $file = $this->getOption('cache_dir') . $this->getOption('cache_prefix') . $this->_cacheId; 
  154.         @unlink($file); 
  155.         //删除附合条件的输出缓存 
  156.         $file = $this->getOption('page_dir') . $this->getOption('cache_prefix') . $this->_cacheId; 
  157.         @unlink($file); 
  158.     } 
  159.     
  160.     /** 
  161.      * 保存输出缓存,并设置缓存过期时间 
  162.      * @param int $lifeTime 缓存过期时间 
  163.      */ 
  164.     public function end($lifeTime = null){ 
  165.  
  166.         if(null !== $lifeTime
  167.             $this->setOption('life_time'$lifeTime); 
  168.     
  169.         $file = $this->getOption('page_dir') . $this->getOption('cache_prefix') . $this->_cacheId; 
  170.         $data = ob_get_contents(); 
  171.         ob_end_clean(); 
  172.         @file_put_contents($file$data); 
  173.         @chmod($file, 0777); 
  174.         @touch($file, time() + $this->getOption('life_time'])); 
  175.     } 
  176.     
  177.     /** 
  178.      * 根据参数清除相应缓存 
  179.      * @param string $mode 缓存类型,包括(CLEANING_MODE_ALL:所有缓存, CLEANING_MODE_OLD: 过期缓存) 
  180.      */ 
  181.     public function clear($mode = CLEANING_MODE_OLD){ 
  182.     
  183.         $dirs = array('cache_dir''page_dir'); 
  184.         foreach($dirs as $value){ 
  185.             if(null != $this->getOption($value)){ 
  186.                 $files = scandir($this->getOption($value)); 
  187.                 switch ($mode) { 
  188.  
  189.                     case CLEANING_MODE_ALL: 
  190.                     default
  191.                         foreach ($files as $val){ 
  192.                             @unlink($this->getOption($value) . $val); 
  193.                         } 
  194.                         break
  195.  
  196.                     case CLEANING_MODE_OLD: 
  197.                     default
  198.                         foreach ($files as $val){ 
  199.                             if (filemtime($this->getOption($value) . $val) < time()){  
  200.                                 @unlink($this->getOption($value) . $val);  
  201.                             } 
  202.                         } 
  203.                         break
  204.                 } 
  205.             } 
  206.         } 
  207.     } 
  208.     
  209.     /** 
  210.      * 取临时文件夹为缓存文件夹 
  211.      * @return $dir 临时文件夹路径 
  212.      */ 
  213.     public function getTmpDir(){ 
  214.     
  215.         $tmpdir = array(); 
  216.         foreach (array($_ENV$_SERVERas $tab) { 
  217.             foreach (array('TMPDIR''TEMP''TMP''windir''SystemRoot'as $key) { 
  218.                 if (isset($tab[$key])) { 
  219.                     if (($key == 'windir'or ($key == 'SystemRoot')) { 
  220.                         $dir = realpath($tab[$key] . '\temp'); 
  221.                     } else { 
  222.                         $dir = realpath($tab[$key]); 
  223.                     } 
  224.                     if ($this->_isGoodTmpDir($dir)) { 
  225.                         return $dir
  226.                     } 
  227.                 } 
  228.             } 
  229.         } 
  230.         $upload = ini_get('upload_tmp_dir'); 
  231.         if ($upload) { 
  232.             $dir = realpath($upload); 
  233.             if ($this->_isGoodTmpDir($dir)) { 
  234.                 return $dir
  235.             } 
  236.         } 
  237.         if (function_exists('sys_get_temp_dir')) { 
  238.             $dir = sys_get_temp_dir(); 
  239.             if ($this->_isGoodTmpDir($dir)) { 
  240.                 return $dir
  241.             } 
  242.         } 
  243.         //通过尝试创建一个临时文件来检测 
  244.         $tempFile = tempnam(md5(uniqid(rand(), TRUE)), ''); 
  245.         if ($tempFile) { 
  246.             $dir = realpath(dirname($tempFile)); 
  247.             unlink($tempFile); 
  248.             if ($this->_isGoodTmpDir($dir)) { 
  249.                 return $dir
  250.             } 
  251.         } 
  252.         if ($this->_isGoodTmpDir('/tmp')) { 
  253.             return '/tmp'
  254.         } 
  255.         if ($this->_isGoodTmpDir('\temp')) { 
  256.             return '\temp'
  257.         } 
  258.         throw new Exception('无法确定临时目录,请手动指定cache_dir', E_USER_ERROR); 
  259.     } 
  260.  
  261.     /** 
  262.      * 验证给定的临时目录是可读和可写的 
  263.      * 
  264.      * @param string $dir 临时文件夹路径 
  265.      * @return boolean true or false 临时文件夹路径是否可读写 
  266.      */ 
  267.     protected function _isGoodTmpDir($dir){ 
  268.     
  269.         if (is_readable($dir)) { 
  270.             if (is_writable($dir)) { 
  271.                 return true; 
  272.             } 
  273.         } 
  274.         return false; 
  275.     } 
  276. }//endclass 

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论