memcached +mysql+php 测试例子

Posted 菜鸟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>";

}
?>

以上是关于memcached +mysql+php 测试例子的主要内容,如果未能解决你的问题,请参考以下文章

搭建Memcache服务详解

php分页例子实现读取mysql数据分页显示

yum 安装apache php 使php支持memcached扩展

memcache缓存服务器(安装-配置-测试篇)

XHProf的安装和使用(PHP性能测试神器)

多容器配合实现开发环境(nginx+php+memcached+mysql)