概念
memcache 是一个高效的分布式的内存对象缓存系统,他可以支持把php的各种数据(数组,对象,基本数据类型)放在它管理的内存中
原理图
安装memcached
yum install memcached #安装memcached chkconfig --add memcached #设置系统自动启动 vim /etc/init.d/memcached #设置memcached启动的参数
安装memcache client php插件
wget http://pecl.php.net/get/memcache-2.1.2.tgz tar -xvf memcache-2.1.2.tgz cd memcache-2.1.2 phpize && ./configure --enable-memcache && make #拷贝memcache.so到php的扩展module中 #修改php.ini文件,添加extension=memcache.so
代码使用
<?php //1.实例化一个Memcache对象 $mem=new Memcache; //2. 连接到指定的memcache中 $mem->connect("127.0.0.1",11211); //0表示不压缩数据,如果使用压缩MEMCACHE_COMPRESSED if(!$mem->add("name","test1",0,30)){ echo "name 已经存在了"; }else{ echo "ok!"; } //可以放入数值 if(!$mem->add("age",100,0,30)){ echo "age 已经存在了"; }else{ echo "ok!"; } //可以放入boolean if(!$mem->set("ok",true,0,30)){ echo "ok 保存成功"; }else{ echo "ok!"; } //放入数组 $arr1=array("aa"=>"北京","bb"=>"天津"); //对数组进行序列化,在网络传输的时候,为了保证,数据类型的不丢失, //先序列化,再发生. //$arr1=serialize($arr1); $arr2=json_encode($arr1); print_r($arr2); $mem->add("arr",$arr1,MEMCACHE_COMPRESSED,100); //对象 require "Person.class.php"; $person=new Person(10,"xiaoming"); $mem->add("per1",$person,MEMCACHE_COMPRESSED,100); //取出 $per2=$mem->get("per1"); var_dump($per2); echo "对象名字=".$per2->name; //string, int,float, boolean array object null resource //不能把resource 类型放入到memcache $con=mysql_connect("localhost","root","root"); echo "<br/>"; var_dump($con); $mem->add("mylink",$con); ?> 关于如何使用多个memcached 缓存服务器. <?php $mem=new Memcache(); //如果我们网站,需要多个memached缓存系统. //$mem->connect("localhost",11211); (立即向localhost的11211端口发出连接) $mem->addServer("192.168.1.100",11211);//256 ->10m $mem->addServer("192.168.1.200",11211); $mem->addServer("192.168.1.222",11211); //创建多个memcache服务使用. //addServer 会根据负载均衡算法,自动放入每个服务器 $mem->add("name","zs",0,100); ?>
注意:string, int,float, boolean array object null resource 中除了 resource 不能存放,其它都可以.