VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > PHP >
  • 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.   } 
  43. } 

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; 
  31. } 

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

memcache缓存

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

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

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

出处:http://www.phpfensi.com/php/20140730/4059.html


相关教程