通过该接口可以很容易的使用 Redis进行 分布式session处理,性能不会有太大问题,但对session提供了分布式存储的方案
class RedisSessionHandler implements SessionHandlerInterface{ |
private $session_id = null; |
private $maxlifetime = null; |
public function __construct( $namespace , $host , $port ) { |
$this ->redis = new Redis(); |
$this ->redis->connect( $this ->config[ 'host' ], $this ->config[ 'port' ]); |
$this -> namespace = $namespace ; |
$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是否已经存在 |
if ( $this ->session_id && $this ->session_id != $id ){ |
$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" ); |
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 ); |
public function gc( $maxlifetime ){ |
private function session_id(){ |
$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); |
"redis_host" => '127.0.0.1' , |
$handler = new RedisSessionHandler( $param [ 'namespace' ], $param [ 'redis_host' ], $param [ 'redis_port' ]); |
session_set_save_handler( $handler , true); |
}
|