好久没有写博客了,今天来一片php使用redis共享session

网上的php将session存放在redis的方法,大多数只是指出了如何存放,并没有涉及到如何存放json格式

我根据网上的资料,整理出自己的代码,使得session能够以json格式存放在redis里面,方便和其他语言的共享


<?php
class RedisSessionHandler implements SessionHandlerInterface{
	private $redis;
	private $config;
	private $namespace;
	private $session_id = null;
	private $maxlifetime = null;


	public function __construct($config) {
		//初始化redis
		$this->config = array(
				'namespace'=>'',
				'host'=>'127.0.0.1',
				'port'=>'6789',
				'auth'=>'',
				'db'=>0
				);
		$this->config = array_merge($this->config,$config);
		$this->redis = new Redis();
		$this->redis->connect($this->config['host'],$this->config['port']);
		if(!empty($this->config['auth']))
		{
			$ret = $this->redis->auth($this->config['auth']);
			if(!$ret)
			{
				return false;
			}
			$this->redis->select($this->config['db']);
		}
		//设置当前的sessionid生成的命名空间
		$this->namespace = $this->config['namespace'];
		if(!empty($this->namespace))
		{
			$this->namespace .=':';
		}
		//设置初始化的session_id
		if(empty($session_name))
		{
			$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;
		if(!empty($this->config['auth']))
		{
			$ret = $this->redis->auth($this->config['auth']);
			if(!$ret)
			{
				return false;
			}
			$this->redis->select($this->config['db']);
		}
		//在初次设置的时候,重设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){
		$data = json_decode($this->redis->get($this->namespace.$id),TRUE);
		return serialize($data);
	}
	public function write($id, $data){
		$json = json_encode(unserialize($data),JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
		return $this->redis->setex($this->namespace.$id,$this->maxlifetime,$json);
	}
	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);
	}
}


$handler = new RedisSessionHandler($param);
session_set_save_handler($handler, true);
session_start();
/*
   if(empty($_SESSION)){
   $_SESSION['test']= ['a'=>1,'b'=>2];
   }
   var_dump($_SESSION);
 */



需要把session.serialize_handler 设置为php_serialize




原理:自己写代码实现SessionHandlerInterface 接口,在写入和读出时进行格式转换,使得session能够以json格式存放在redis里面。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 添加Redis依赖库 在项目的pom.xml文件中添加Redis的依赖库。 ```xml <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.3.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.0.0</version> </dependency> ``` 2. 配置Redis连接池 在SpringMVC的配置文件中添加Redis的连接池配置。 ```xml <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="localhost"/> <property name="port" value="6379"/> <<property name="password" value="password"/>> <property name="poolConfig"> <bean class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="1000"/> <property name="maxIdle" value="100"/> <property name="minIdle" value="10"/> <property name="maxWaitMillis" value="10000"/> </bean> </property> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/> </bean> ``` 3. 配置Session共享 在SpringMVC的配置文件中添加Session共享的配置。 ```xml <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <property name="maxInactiveIntervalInSeconds" value="1800"/> </bean> <bean class="org.springframework.session.web.http.CookieHttpSessionIdResolver"> <constructor-arg name="cookieName" value="SESSION_ID"/> <property name="cookiePath" value="/"/> <property name="cookieMaxAge" value="-1"/> </bean> ``` 4. 启用Session共享 在SpringMVC的配置文件中启用Session共享。 ```xml <bean class="org.springframework.session.web.http.SessionRepositoryFilter"> <constructor-arg> <bean class="org.springframework.session.data.redis.RedisOperationsSessionRepository"> <constructor-arg ref="redisTemplate"/> </bean> </constructor-arg> </bean> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="sessionAttributeStore"> <bean class="org.springframework.session.web.http.SessionRepositoryFilter"> <constructor-arg> <bean class="org.springframework.session.data.redis.RedisOperationsSessionRepository"> <constructor-arg ref="redisTemplate"/> </bean> </constructor-arg> </bean> </property> </bean> ``` 5. 测试 启动项目后,访问任意一个页面,然后在Redis中就可以看到Session的信息了。 ```shell redis-cli 127.0.0.1:6379> keys * 1) "spring:session:sessions:5b5d4b4f-9a9f-4e4e-bd56-4b4c7f1d8f0b" 127.0.0.1:6379> get spring:session:sessions:5b5d4b4f-9a9f-4e4e-bd56-4b4c7f1d8f0b "\xac\xed\x00\x05sr\x00\x17java.util.HashMap\x85\x95\x1d\x9b\x94\xee\x0c\x00\x00\x03I\x00\x05valuexr\x00\x10java.lang.String\x86\xac\xed\x00\x05sr\x00\x11java.lang.String\x12\xe2\xa0\xa4\xf7\x81\x878\x02\x00\x01Ljava/lang/String;L\x00\x04namet\x00\x12Ljava/lang/String;L\x00\x08usernameq\x00~\x00\x01sq\x00~\x00\x0bpasswordq\x00~\x00\x0b" ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值