MEMCACHE共享SESSION

admin 发布于:2014-1-10 11:42 分类:系统架构  有 2118 人浏览,获得评论 0 条 标签: session memcache 

1. 实验环境(2个机器)
192.168.1.10(Memcached服务器)
192.168.1.20(WEB服务器)
2.配置Memcached服务器(192.168.1.10)
安装: yum install memcached
开启: memcached -d -m 32 -p 11211 -u root (开启11211端口提供服务,32M缓存,最好不要带-l 如 -l 127.0.0.1,否则会导致远程服务器连接不上)
3.在WEB机器上编写测试程序(192.168.1.20. 注意:一定要安装memcache扩展)
<?php
header("Content-type:text/html; charset=utf-8");
echo "<pre>";
$mamcache_server_ip='192.168.1.10';
$mamcache_server_port='11211';

//设置MemcacheSession共享
ini_set("session.save_handler","memcache");
ini_set("session.save_path","tcp://$mamcache_server_ip:$mamcache_server_port");
session_start();


//session赋值
$session_id=session_id();
var_dump("session_id=".$session_id);


$action=$_GET['action'];
switch($action)
{
	
	
	//清除$_SESSION['mem_session']
	case 'clear':
	unset($_SESSION['mem_session']);
	var_dump($_SESSION['mem_session']);
	//session_destroy();
	break;
	
	//存储SESSION
	case 'set':
	$_SESSION['mem_session']='测试SESSION='.date("Y-m-d H:i:s"); 
	var_dump($_SESSION['mem_session']);
	break;
	
	//获取SESSION
	case 'get':
	var_dump($_SESSION['mem_session']);
	break;
	
	
	//查看Memcahce如何存储的SESSION
	case 'mem':
	//从MEMCACHE读取SESSION的值。
	$memcache = new Memcache;
	$memcache->connect($mamcache_server_ip,$mamcache_server_port) or die ("连接服务器失败");
	
	//key 来源 session_id();
	$result = $memcache->get($session_id);
	var_dump("结果=".$result);
	break;
}

echo "</pre>";
?>
4. 测试结果如下:
4.1. http://localhost/session.php?action=clear
string(37) "session_id=o8lb038n05c6e185d0c882kp84"
NULL
4.2. http://localhost/session.php?action=set
string(37) "session_id=o8lb038n05c6e185d0c882kp84"
string(33) "测试SESSION=2014-01-10 05:32:46"


4.3.http://localhost/session.php?action=get
string(37) "session_id=o8lb038n05c6e185d0c882kp84"
string(33) "测试SESSION=2014-01-10 05:32:46"



4.4.http://localhost/session.php?action=mem


string(37) "session_id=o8lb038n05c6e185d0c882kp84"
string(60) "结果=mem_session|s:33:"测试SESSION=2014-01-10 05:32:46";"