首页 > mysql > memcached +mysql+php 测试例子

memcached +mysql+php 测试例子

2010年5月18日 eric 发表评论 阅读评论

最近看了看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', 'eric@nginxs.com'
);

创建一个 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>";

}
?>

测试 第一次访问 提示 mysql

刷新,第二次访问,提示memcache

转载请注明:文章转载自:Eric's linux and nginx! (http://www.nginxs.com)
本文地址:http://www.nginxs.com/linux/152.html

分类: mysql 标签: , ,
评论分页
1 ... 3 4 152
订阅评论
0+7= (必填)