<?php
$memcache = new Memcache;
$memcache->connect('192.168.154.131', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."
";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)
";
$get_result = $memcache->get('key');
echo "Data from the cache:
";
var_dump($get_result);
?>
预计会输出四行字符,有memcache版本信息等
(成功表示连接到了memcache服务器)
编写测试memcache的session共享脚本,vim /usr/local/nginx/html/session.php
<?php
session_start();
if (!isset($_SESSION['session_time']))
{
$_SESSION['session_time'] = time();
}
echo "now_time:".time()."
";
echo "session_id:".session_id()."
";
?>
预计输出session_time、now_time、session_id
使用telnet连接memcache
telnet 192.168.154.131 11211
然后get session_id的值,如果得到的session_time和网页上的一样表示session共享成功。
在mysql上
mysql> create database testdb1;
mysql> use testdb1;
mysql> create table test1(id int not null auto_increment,name varchar(20) default null,primary key (id)) engine=innodb auto_increment=1 default charset=utf8;
mysql> insert into test1(name) values ('tom1'),('tom2'),('tom3'),('tom4'),('tom5');
mysql> select * from test1;
+----+------+
| id | name |
+----+------+
| 1 | tom1 |
| 2 | tom2 |
| 3 | tom3 |
| 4 | tom4 |
| 5 | tom5 |
+----+------+
5 rows in set (0.00 sec)
mysql> grant select on testdb1.* to user@'%' identified by '123456';
在nginx上
编辑memcache缓存mysql测试页面,vim /usr/local/nginx/html/test_db.php
<?php
$memcachehost = '192.168.154.131';
$memcacheport = 11211;
$memcachelife = 60;
$memcache = new Memcache;
$memcache->connect($memcachehost,$memcacheport) or die ("Could not connect");
$query="select * from test1 limit 10";
$key=md5($query);
if(!$memcache->get($key))
{
$conn=mysql_connect("192.168.154.134","user","123456");
mysql_select_db(testdb1);
$result=mysql_query($query);
while ($row=mysql_fetch_assoc($result))
{
$arr[]=$row;
}
$f = 'mysql';
$memcache->add($key,serialize($arr),0,30);
$data = $arr ;
}
else{
$f = 'memcache';
$data_mem=$memcache->get($key);
$data = unserialize($data_mem);
}
echo $f;
echo "<br>"
echo "$key";
echo "<br>"
//print_r($data);
foreach($data as $a)
{
echo "number is <b><font color=#FF0000>$a[id]</font></b>";
echo "<br>";
echo "name is <b><font color=#FF0000>$a[name]</font></b>";
echo "<br>";
}
?>
预计会输出memcache的key,和我们在mysql创建的数据表的数据
(成功即表示memcache缓存到mysql的数据)
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx