php中的memcache应用(转)
本文转自:http://www.php100.com/html/itnews/it/2013/0222/12097.html
所需环境:
php 5.3.3
apache 2.2.7
mysql 5.5.8
解压Memcached_1.2.5文档,cmd下执行memcached.exe -d -install
将php5.3_vc6_memcachedll文档解压,将php_memcache.dll文件复制到php安装目录的ext文件目录中。
然后在php.ini 当中填上这句话:extension="php_memcache.dll"
在phpinfo()下查看,是否引用了memcache扩展。
测试代码:
-
1 <?php 2 //连接 3 $mem = new Memcache; 4 $mem->connect("127.0.0.1", 11211); 5 6 //保存数据 7 $mem->set('key1', 'This is first value', 0, 60); 8 $val = $mem->get('key1'); 9 echo "Get key1 value: " . $val ."<br />"; 10 11 //替换数据 12 $mem->replace('key1', 'This is replace value', 0, 60); 13 $val = $mem->get('key1'); 14 echo "Get key1 value: " . $val . "<br />"; 15 16 //保存数组 17 $arr = array('aaa', 'bbb', 'ccc', 'ddd'); 18 $mem->set('key2', $arr, 0, 60); 19 $val2 = $mem->get('key2'); 20 echo "Get key2 value: "; 21 print_r($val2); 22 echo "<br />"; 23 24 //删除数据 25 $mem->delete('key1'); 26 $val = $mem->get('key1'); 27 echo "Get key1 value: " . $val . "<br />"; 28 29 //清除所有数据 30 $mem->flush(); 31 $val2 = $mem->get('key2'); 32 echo "Get key2 value: "; 33 print_r($val2); 34 echo "<br />"; 35 //关闭连接 36 $mem->close(); 37 38 $memcachehost = '192.168.10.1'; 39 $memcacheport = 11211; 40 $memcachelife = 60; 41 $memcache = new Memcache; 42 $memcache->connect($memcachehost,$memcacheport) or die ("Could not connect"); 43 $query="select * from user limit 10"; 44 $key=md5($query); 45 if(!$memcache->get($key)) 46 { 47 $conn=mysql_connect("192.168.30.1","root","passwd"); 48 mysql_select_db(users); 49 $result=mysql_query($query); 50 while ($row=mysql_fetch_assoc($result)) 51 { 52 $arr[]=$row; 53 } 54 $f = 'db'; 55 $memcache->add($key,serialize($arr),0,30); 56 $data = $arr ; 57 } 58 else{ 59 $f = 'mem'; 60 $data_mem=$memcache->get($key); 61 $data = unserialize($data_mem); 62 } 63 echo $f; 64 echo ""; 65 //print_r($data); 66 foreach($data as $a) 67 { 68 echo $a[user_id]._.$a[email]; 69 echo ""; 70 } 71 ?>
新闻系统的应用:
-
1 //==============memcache 2 $memcachehost = '127.0.0.1'; 3 $memcacheport = 11211; 4 $memcachelife = 60; 5 $memcache = new Memcache; 6 $memcache->connect($memcachehost,$memcacheport) or die ("Could not connect"); 7 //==============新闻 8 9 $sql="SELECT id,title,left(title,16) as biaoti,date_time FROM `p_newsbase` where shenhe='1' order by id DESC limit 7 "; 10 $query=$db->query($sql); 11 $key=md5($query); 12 while($row_news=$db->fetch_array($query)){ 13 $str=$row_news['biaoti'].$db->time_out($row_news['date_time']); 14 $sm_news[]=array("name"=>$str,"title"=>$row_news['title'],"id"=>$row_news['id'],"date_time"=>$row_news['date_time']); 15 16 } 17 if(!$memcache->get($key)){ 18 $memcache->add($key,serialize($sm_news),0,$memcachelife); 19 }else{ 20 $data_mem=$memcache->get($key); 21 $sm_news = unserialize($data_mem); 22 } 23 $smarty->assign("sm_news",$sm_news);