memcached +mysql+php 测试例子

最近看了看memcached 缓存 mysql,经过一段时间的研究·把自己测试方法写出来,给像我一样的初学者用~
我的环境是 nginx + php-fpm + apc + mysql

编译安装memcached

tar zxvf memcached-1.4.0.tar.gz
cd memcached-1.4.0
./configure --prefix=/usr
make
make install


启动memcached

memcached -d -m 64 -u root -l 192.168.6.191 -p 11211 -c 64 -P /tmp/memcached.pid
/usr/local/mysql/bin/mysql -uroot -p



创建一个测试数据库 mydb

create database mydb;


创建一个空的数据表 personal_info

CREATE TABLE `personal_info` (
`pi_id` bigint(20) NOT NULL auto_increment,
`pi_name` varchar(50) NOT NULL,
`pi_tel` varchar(15) default NULL,
`pi_qq` varchar(15) default NULL,
`pi_email` varchar(50) default NULL,
PRIMARY KEY (`pi_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;


给表插入数据

INSERT INTO `mydb`.`personal_info` (
`pi_id` ,
`pi_name` ,
`pi_tel` ,
`pi_qq` ,
`pi_email`
)
VALUES (
‘1‘, ‘eric‘, ‘13611031222‘, ‘55555555‘, ‘[email protected]
);


创建一个 php 文件 mysql-memcache.php

<?php
$memcachehost = ‘192.168.6.191‘;
$memcacheport = 11211;
$memcachelife = 60;
$memcache = new Memcache;
$memcache->connect($memcachehost,$memcacheport) or die ("Could not connect");
$query="select * from personal_info limit 10";
$key=md5($query);
if(!$memcache->get($key))
{
                $conn=mysql_connect("localhost","root","passwd");
                mysql_select_db(mydb);
                $result=mysql_query($query);
                while ($row=mysql_fetch_assoc($result))
                {
                        $arr[]=$row;
                }
                $f = ‘mysql‘;
                $memcache->add($key,serialize($arr),0,30);        //mysql 查询后,插入 memcached
                $data = $arr ;
}
else{
        $f = ‘memcache‘;
        $data_mem=$memcache->get($key);
        $data = unserialize($data_mem);
}
echo $f;
echo "<br>";
//print_r($data);
foreach($data as $a)
{
                echo "number is <b><font color=#FF0000>$a[pi_id]</font></b>";
                echo "<br>";
                echo "name is <b><font color=#FF0000>$a[pi_name]</font></b>";
                echo "<br>";
                echo "tel is <b><font color=#FF0000>$a[pi_tel]</font></b>";
                echo "<br>";
                echo "qq is <b><font color=#FF0000>$a[pi_qq]</font></b>";
                echo "<br>";
                echo "email is <b><font color=#FF0000>$a[pi_email]</font></b>";
                echo "<br>";

}
?>

其他相关参考文章:

1)php操作Memcached缓存系统:http://www.open-open.com/lib/view/open1372256456713.html

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。