Posted by:
努力记

努力记,通过记录,计划,让自己的努力可以触碰彩虹!

6,432

PHP:用Redis存储session

  • 2014-08-02
  • 暂无评论
PHP在5.3提供了一个SessionHandler接口,可以自定义处理session的存储方案
通过该接口可以很容易的使用Redis进行分布式session处理,性能不会有太大问题,但对session提供了分布式存储的方案

<?php
class RedisSessionHandler implements SessionHandlerInterface{
    private $redis;
 private $config;
 private $namespace;
 private $session_id = null;
 private $maxlifetime = null;
 
 public function __construct($namespace,$host,$port) {
  //初始化redis
  $this->config = array(
   'host'=>$host,
   'port'=>$port
  );
  $this->redis = new Redis();
  $this->redis->connect($this->config['host'],$this->config['port']);
  //设置当前的sessionid生成的命名空间
  $this->namespace = $namespace;
  //设置初始化的session_id
  $session_name = ini_get("session.name");
  //没有设置过session,新的会话,需要重新生成sessionid
  if ( empty($_COOKIE[$session_name]) ) {
   $this->session_id = true;
  }
 }
    public function open($savePath, $sessionName){
  $connect = $this->redis->connect($this->config['host'],$this->config['port']);
  if(!$connect) return false;
  //在初次设置的时候,重设PHP本身的session_id并判断session_id是否已经存在
  $id = session_id();
  if($this->session_id && $this->session_id != $id){
   do{
    $this->session_id = $this->session_id();
   }while($this->redis->exists($this->namespace.'@'.$this->session_id));
   session_id($this->session_id);
  }
  //设置生成周期
  $this->maxlifetime = ini_get("session.gc_maxlifetime");
        return true;
    }
    public function close(){
  $this->redis->close();
        return true;
    }
    public function read($id){
        return $this->redis->get($this->namespace.'@'.$id);
    }
    public function write($id, $data){
  return $this->redis->setex($this->namespace.'@'.$id,$this->maxlifetime,$data);
    }
    public function destroy($id){
  $this->redis->delete($this->namespace.'@'.$id);
        return true;
    }
    public function gc($maxlifetime){
        return true;
    }
 /**
  * 生成guid
  */
 private function session_id(){
  $uid = uniqid("", true);
  $data = $this->namespace;
  $data .= $_SERVER['REQUEST_TIME'];
  $data .= $_SERVER['HTTP_USER_AGENT'];
  $data .= $_SERVER['SERVER_ADDR'];
  $data .= $_SERVER['SERVER_PORT'];
  $data .= $_SERVER['REMOTE_ADDR'];
  $data .= $_SERVER['REMOTE_PORT'];
  $hash = strtoupper(hash('ripemd128', $uid . md5($data)));
  return substr($hash,0,32);
 }
}
$param = array(
  "namespace"=>'',
  "redis_host"=>'127.0.0.1',
  "redis_port"=>'6379'
 );
if($param){
 $handler = new RedisSessionHandler($param['namespace'],$param['redis_host'],$param['redis_port']);
 session_set_save_handler($handler, true);
}

 



back up ↑

无觅相关文章插件,快速提升流量