参考:http://deidara.blog.51cto.com/400447/317526/
一、测试环境:
二、测试步骤:
1、完成基础环境的搭建(nginx+php-fpm+memcache+memcached+mysql)
注意:
nginx+php-fpm与mysql环境的分离
php如何扩展模块memcache
memcache与memcached的区别
2、启动这个环境,保证能够正常的启动
注意:
启动memcached:
memcached -d -m 100 -l 192.168.1.120 -p 11211 -u root
3、数据库授权用户test和IP地址可以访问数据库jiang
grant all on jiang.* to 'test'@'192.168.1.120' identified by 'test';
4、创建数据库和表内容
create database jiang;
mysql> use jiang;
mysql> 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 ;
mysql> INSERT INTO `jiang`.`personal_info` (
`pi_id` ,
`pi_name` ,
`pi_tel` ,
`pi_qq` ,
`pi_email`
)
VALUES (
'1', 'jiang', '1586544556', '42423423', '[email protected]'
);
mysql> select * from personal_info
-> ;
+-------+---------+------------+----------+--------------------+
| pi_id | pi_name | pi_tel | pi_qq | pi_email |
+-------+---------+------------+----------+--------------------+
| 1 | jiang | 1586544556 | 42423423 | [email protected] |
+-------+---------+------------+----------+--------------------+
5、php测试代码(原理,如果memecached中有查询的值,则直接读取,如果没有从mysql数据库读取,并重新写一份到memcached中)
<?php
$memcachehost = '192.168.1.120';
$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("192.168.1.121","test","test");
mysql_select_db(jiang);
$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>";
echo "key:";
print_r($key);
echo "<br>";
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>";
}
?>
6、测试结果
访问:http://192.168.1.120/memsql.php
telnet 192.168.1.120
get 76fc3b222d217ac77d6797672fb09eb1 #执行get key就可以获取memcached缓存的内容
VALUE 76fc3b222d217ac77d6797672fb09eb1 0 161
a:1:{i:0;a:5:{s:5:"pi_id";s:1:"1";s:7:"pi_name";s:5:"jiang";s:6:"pi_tel";s:10:"1586544556";s:5:"pi_qq";s:8:"42423423";s:8:"pi_email";s:18:"[email protected]";}}