在php中使用Memcache

1、安装memcache扩展

首先咱们经过phpinfo()函数查看一下咱们当前的php环境是否支持memcache扩展,在服务器的根目录下新建一个文件info.php,在文件中写入php

 

1
2
<?php
     phpinfo();

 

而后在浏览器中输入 http://localhost/info.php  访问,而后查找是否有memcache扩展,通常咱们的服务器默认是没有安装memcache扩展的,因此仍是得咱们本身来安装。咱们先到网上下载 php_memcache.dll文件,把文件拷贝到php扩展目录下(个人是php5/ext/),在扩展目录下加上这个文件还没完成,咱们要在php 的配置文件php.ini文件中加入extension=php_memcache.dll,php环境会自动找到php扩展目录将这个扩展加到php环 境中,这个时候咱们再重启apache,而后再来访问 http://localhost/info.php ,就能够看到mysql

这就说明咱们的memcache扩展安装好了!咱们再查看php手册,发现memcache扩展的使用有两种方式,第一种是面向过程的使用方式,还有一种是面向对象的使用方式,而咱们通常经常使用的是面向对象的方式。web

    2、memcache的使用实例

直接贴代码了!sql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
     //实例化memcache类
     $mem  new  Memcache;
    
     //链接memcache服务器(参数为服务器IP, 端口),
     //pconnect--表示持续链接
     $mem ->connect( 'localhost' , 11211);
    
     //addserver表示增长memcache服务器, 
     //多个memcache服务器能够实现分布式缓存
     //$mem->addsever('www.pccxin.com', 11211);
     //$mem->addsever('www.frontu.net', 11211);
    
     //向memcache服务器中增长元素
     //bool Memcache::add ( string $key , 
     //mixed $var [, int $flag [, int $expire ]] )
     //参数为 键名, 值(字符串|数组|对象), 
     //使用 MEMCACHE_COMPRESSED 标记对数据进行压缩(使用zlib), 
     // 保存时间(单位秒)
     $mem ->add( 'mystr' 'This is my first memcache test!'
         MEMCACHE_COMPRESSED, 3600);
    
     //add不会重复添加,要想改变值可用replace(),或者set
     //$mem->add('mystr', 'This is my first memcache test!', 
         MEMCACHE_COMPRESSED, 3600); 
     
         //向服务器中保存数据
     $mem ->set( 'mystr' 'This is my second memcache test!' ,
          MEMCACHE_COMPRESSED, 3600); 
    
     //从服务端删除一个元素
     //$mem->delete('mystr');
    
     //清洗(删除)已经存储的全部的元素
     //$mem->flush();
    
     //获取memcache中的数据
     echo  $mem ->get( 'mystr' ). '<br />' ;
    
     //向memcache服务器中增长元素
     $mem ->add( 'myarr' array ( '1' => 'aaa' '2' => 'bb' '3' => 'cc' ),
          MEMCACHE_COMPRESSED, 3600);
     var_dump( $mem ->get( 'myarr' ));
     echo  '<br />' ;
    
    
     class  Person{
         var  $name  'shawnking' ;
         var  $sex  '男' ;
     }
    
     //向memcache服务器中增长元素
     $mem ->add( 'myobj' new  Person);
    
     var_dump( $mem ->get( 'myobj' ));
     echo  '<br />' ;
    
    
     //获取memcache的版本信息
     echo  'Version:' , $mem ->getVersion();
    
     //获得memcache的参数信息
     echo  '<pre>' ;
     print_r( $mem ->getStats());
     echo  '</pre>' ;
    
     //关闭到memcached服务端的链接。这个函数不会关闭持久化链接,
     // 持久化链接仅仅会在web服务器关机/重启时关闭。与之对应的,你也能够使用 
     $mem ->close();  

     3、php在什么地方使用memcache

        a、数据库中读出来的数据(select) 使用memcache处理

一般状况下咱们访问一次页面php就会链接一次数据库,就会到数据库中读取数据,若是访问量大的时候数据库就没法承受压力了,咱们使用 memcache的 话,只要页面第一次被访问php就会把数据存到memcache服务器中,而且设定一个过时时间,这样在过时时间以前都不须要去数据库读取数据,这个能够 大大提成网站性能(咱们memcache的数据是存在内存中的,因此读取起来很是快)。下面我就贴出在数据库中使用memcache的示例代码:数据库

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
     //实例化一个memcache对象
     $mem  new  Memcache;
    
     //链接memcache服务器
     $mem ->connect( 'localhost' , 11211);
    
     /**
      * 注意:
      *    一、同一个项目安装两次,key要有前缀
      *        $key = 'a_test';
      *        $key = 'b_test';
      *    二、 用sql语句做为下标,这样可让相同sql语句的数据只要存一份到memcache       
      */
    
     $sql  'SELECT * FROM test' ;
     $key  substr (md5( $sql ), 10, 8);
    
     //从memcache服务器获取数据
     $data  $mem ->get( $key );
    
    
     //判断memcache是否有数据
     if ( ! $data  ){
        
         $mysqli  new  mysqli( 'localhost' 'root' '123456' 'testdb' );
        
         $result  =   $mysqli ->query( $sql );
        
         $data  array ();
        
         while $row = $result ->fetch_assoc() ){
             $data [] =  $row ;
         }
        
         $result ->free(); //释放内存
         $mysqli ->close(); //断开mysql链接
        
         //向memcache服务器存储数据,还要设置失效时间(单位为秒)
         $mem ->set( $key $data , MEMCACHE_COMPRESSED, 3600);
        
      }
     
      print_r( $data );
      $mem ->close();  //关闭memcache链接
        b、在会话控制session中使用
         将session信息写入到memcache服务器当中
<?php
     /**
      * session保存到memcache类
      */
     class  MemSession{
    
         private  static  $handler  = null;
         private  static  $lifetime  = null;
         private  static  $time  = null;
         const  NS =  'session_' ;
        
         /**
          * 初始化函数
          */
         private  static  function  init( $handler ){
             self:: $handler  $handler ;
             self:: $lifetime  ini_get ( 'session.gc_maxlifetime' );
            
             self:: $time  = time();
         }
        
         public  static  function  start(Memcache  $memcache ){
             self::init( $memcache );
            
             session_set_save_handler(
                 array ( __CLASS__ 'open' );
                 array ( __CLASS__ 'close' );
                 array ( __CLASS__ 'read' );
                 array ( __CLASS__ 'write' );
                 array ( __CLASS__ 'destrory' );
                 array ( __CLASS__ 'gc' );
             );
             session_start();
         }
        
         public  static  function  open( $path $name ){
             return  true;
         }
        
         public  static  function  close(){
             return  true;
         }
        
         public  static  function  read( $PHPSESSID ){
             $out  = self:: $handler ->get(self:: $session_key ( $PHPSESSID ));
            
             if $out  === false ||  $out  = null ) 
                 return  '' ;
             return  $out ;
         }
        
         public  static  function  write( $PHPSESSID $data ){
             $method  $data  'set'  'replace' ;
             return  self:: $handler -> $method (self:: $session_key ( $PHPSESSID ),
                      $data , MEMCACHE_COMPRESSED, self:: $lifetime );
         }
        
         public  static  function  destroy( $PHPSESSID ){
             return  sele:: $handler -> delete (self:: $session_key ( $PHPSESSID ));
         }
        
         public  static  function  gc( $lifetime ){
             return  true;
         }
        
         private  static  session_key( $PHPSESSID ){
             $session_key  = self::NS. $PHPSESSID ;
             return  $session_key ;
         }
     }
    
     $memcache  new  Memcache;
    
     $memcache ->connect( 'localhost' , 11211)  or  die ( 'could not connect!' );
    
     MemSession::start( $memcache );

 

     4、memcache的安全(不让别人访问)

一、内网链接apache

二、设置防火墙数组

iptables -A INPUT -p tcp -dport 11211 -j DROP 来拒绝所有的访问,浏览器

再设置能够访问的IP缓存

iptables -A INPUT -p tcp -s 192.168.1.111 -dport 11211 -j ACCEPT安全

iptables -A INPUT -p udp -s 192.168.1.111 -dpost 11211 -j ACCEPT

相关文章
相关标签/搜索