默认情况下,我们的PHP是以文件的形式保存Session数据,所以,每次读写会话信息,就需要去访问硬盘。
为了解决会话信息夸域名问题,即为了实现同一时刻只能一个地方登录,同时也解决读写会话信息必须访问磁盘问题,我想到了,将Session保存到Redis中。下面贴代码:sessionRedis::setSessionHandler();class sessionRedis{public static $redis;public static function sessionOpen($savePath,$sessionName){self::$redis = new Redis();self::$redis->connect(RedisHost,RedisPort);self::$redis->select(3);return true;}public static function sessionClose(){return true;}public static function sessionRead($sessionId){$data = self::$redis->get($sessionId);return $data;}public static function sessionWrite($sessionId,$data){$userId = self::getUserId();if(!empty($userId)){$ukey = 'uid' . $userId;if(self::$redis->hExists('uid',$ukey)){$ssid = self::$redis->hGet('uid',$ukey);self::sessionDestroy($ssid);}self::$redis->hSet('uid',$ukey,$sessionId);}//$cache_expire = session_get_cookie_params();$cache_expire = ini_get("session.gc_maxlifetime");self::$redis->setex($sessionId,$cache_expire,$data);return true;}public static function sessionDestroy($sessionId){self::$redis->del($sessionId);return true;}public static function sessionGC($maxlifetime){//self::$redis->persist();return true;}public static function setSessionHandler(){session_set_save_handler(array(__CLASS__,"sessionOpen"),array(__CLASS__,"sessionClose"),array(__CLASS__,"sessionRead"),array(__CLASS__,"sessionWrite"),array(__CLASS__,"sessionDestroy"),array(__CLASS__,"sessionGC"));return true;}/*这里获取登录的用户ID*/public static function getUserId(){return isset($_SESSION['n_userId']) ? $_SESSION['n_userId'] : 0;}}
session.save_handler = redissession.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2"
这样就ok 了!