在php中使用Memcache


在上一篇博客中我写到了memcache的安装和管理,在这一篇博客中我将写到的是在php中如何使用memcache。

    一、安装memcache扩展

         首先我们通过phpinfo()函数查看一下我们当前的php环境是否支持memcache扩展,在服务器的根目录下新建一个文件info.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 ,就可以看到

memcache.png这就说明我们的memcache扩展安装好了!我们再查看php手册,发现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
<?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();  

     三、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);
     
     /**
      * 注意:
      *    1、同一个项目安装两次,key要有前缀
      *        $key = 'a_test';
      *        $key = 'b_test';
      *    2、 用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 );

 

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

            1、内网连接

            2、设置防火墙

                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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM