这个月我们新开发了一个项目,由于使用到了4台机器做web,使用dns做负载均衡,
面图上用户通过DNS的调度(一个域名对应多个ip)分别访问到VM2-VM5上,四台机器都访问VM1上的redis,两个redis值主从结构.
因此需要使用跨服务器的session保存用户登录状态,于是我写了一个跨站的session共享的类
- <?php
-
-
-
-
-
-
-
- class RedisSession{
- var $expire=86400;
- var $sso_session;
- var $session_folder;
- var $cookie_name;
- var $redis;
- var $cache;
- var $expireAt;
-
-
-
-
-
-
-
- function RedisSession($redis,$expire=86400,$cookie_name="sso_session",$session_id_prefix=""){
- $this->redis=$redis;
- $this->cookie_name=$cookie_name;
- $this->session_folder="sso_session:";
-
- if(isset($_COOKIE[$this->cookie_name])){
- $this->sso_session=$_COOKIE[$this->cookie_name];
- }else{
- $this->expire=$expire;
- $this->expireAt=time()+$this->expire;
-
- if(isset($_GET[$this->cookie_name])){
- $this->sso_session=$_GET[$this->cookie_name];
- }else{
- $this->sso_session=$this->session_folder.$session_prefix.md5(uniqid(rand(), true));
- }
- setcookie($this->cookie_name,$this->sso_session,$this->expireAt,"/");
- }
- }
-
-
-
-
-
- function expire($expire=86400){
- $this->expire=$expire;
- $this->expireAt=time()+$this->expire;
-
- setcookie($this->cookie_name,$this->sso_session,$this->expireAt,"/",".greatwallwine.com.cn");
- $this->redis->expireAt($this->sso_session, $this->expireAt);
- }
-
-
-
-
-
-
- function setMutil($array){
- $this->redis->hMset($this->sso_session,$array);
- }
-
-
-
-
-
-
- function set($key,$value){
- $this->redis->hSet($this->sso_session,$key,$value);
- }
-
-
-
-
-
-
- function setObject($key,$object){
- $this->redis->hSet($this->sso_session,$key,serialize($object));
- }
-
-
-
-
-
- function getAll(){
- return $this->redis->hGetAll($this->sso_session);
- }
-
-
-
-
-
-
-
- function get($key){
- return $this->redis->hGet($this->sso_session,$key);
- }
-
-
-
-
-
-
-
- function getObject($key){
- return unserialize($this->redis->hGet($this->sso_session,$key));
- }
-
-
-
-
- function getFromCache($key){
- if(!isset($this->cache)){
- $this->cache=$this->getAll();
- }
- return $this->cache[$key];
- }
-
-
-
-
-
- function del($key){
- return $this->redis->hDel($this->sso_session,$key);
- }
-
-
-
-
- function delAll(){
- return $this->redis->delete($this->sso_session);
- }
- }
- ?>
使用方法:
- <?php
- error_reporting(0);
- $redisHost="192.168.1.2";
- $redisPort="6379";
- $redis = new Redis();
- $redis->connect($redisHost,$redisPort);
- include_once("inc/RedisSession.php");
- $redisSession=new RedisSession($redis);
-
-
-
-
-
-
-
-
- $redisSession->setObject("obj",array("test1"=>array("test2")));
- $obj=$redisSession->getObject("obj");
- print_r($obj);
- die();
- print_r($redisSession->getAll());
-
- print_r($redisSession->get("name"));
-
-
-
- print_r($redisSession->getFromCache("name"));
-
-
-
-
比较常用的估计是set,get,setObject,getOject
我用sso_session:我主要是方便用phpRedisAdmin管理
end
本文出自 “一方有” 博客,请务必保留此出处http://yifangyou.blog.51cto.com/900206/1041040