php专区

 首页 > php专区 > 正则表达式 > php缓存文件技术介绍 - php会话

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

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