Home  >  Article  >  php教程  >  在php中使用Memcache

在php中使用Memcache

WBOY
WBOYOriginal
2016-06-21 08:47:511082browse

   一、安装memcache扩展

 

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

 

            直接贴代码了!

 

    //实例化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').'
';

     

    //向memcache服务器中增加元素

    $mem->add('myarr', array('1'=>'aaa', '2'=>'bb', '3'=>'cc'),

         MEMCACHE_COMPRESSED, 3600);

 

    var_dump($mem->get('myarr'));

    echo '
';

     

     

    class Person{

        var $name = 'shawnking';

        var $sex = '男';

    }

     

    //向memcache服务器中增加元素

    $mem->add('myobj', new Person);

     

    var_dump($mem->get('myobj'));

    echo '
';

     

     

    //获取memcache的版本信息

    echo 'Version:',$mem->getVersion();

     

    //得到memcache的参数信息

    echo '

';
<p>    print_r($mem->getStats());</p>
<p>    echo '</p>
';

     

    //关闭到memcached服务端的连接。这个函数不会关闭持久化连接,

    // 持久化连接仅仅会在web服务器关机/重启时关闭。与之对应的,你也可以使用 

    $mem->close();  

     三、php在什么地方使用memcache

 

            

 

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

 

        通常情况下我们访问一次页面php就会连接一次数据库,就会到数据库中读取数据,如果访问量大的时候数据库就无法承受压力了,我们使用memcache的话,只要页面第一次被访问php就会把数据存到memcache服务器中,并且设定一个过期时间,这样在过期时间之前都不需要去数据库读取数据,这个可以大大提成网站性能(我们memcache的数据是存在内存中的,所以读取起来非常快)。下面我就贴出在数据库中使用memcache的示例代码:

 

  

    //实例化一个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服务器当中

 

    /**

     * 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



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn