使用配置:

1、在pom文件中引入spring-session的jar包

<!--springsession-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>

2、在web.xml中配置springSessionRepositoryFilter过滤器,虽然引入spring-session的jar包默认会创建一个过滤器。

<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter><filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

3、配置RedisHttpSessionConfiguration

在applicationContext.xml中配置bean

<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<!-- 过期时间30分钟 -->
<property name="maxInactiveIntervalInSeconds" value="1800"></property><property name="redisNamespace" value="weijuju-iag-cmb-service-direct"></property>
</bean>

4、使用session.setAttribute保存session时,会保存到redis中。

 

原理分析

1、session的原理

session是存放在服务器端,是服务器端保存状态的载体。当客户端访问服务器时,服务器根据需求设置session,将会话信息保存在服务器上,同时将session的session_id传递给客户端浏览器,浏览器将这个session_id保存至载体上,过期时间为一次会话有效。浏览器关闭后,这个cookie就过期被清理了。

2、session实现共享的方案

因为session是存放在服务器端的,所以在单节点下,session信息理论上不会丢失,但是在多节点部署应用的环境下,session是不能共享的,就会导致,当用户已经登录后,用户登录的信息已经存放在服务器session中,但是根据特定的负载均衡算法会导致用户每次访问不保证一直访问同一台服务器,所以当用户访问另一台服务器时,实际上是拿不到登录信息的。处理session共享的主要方案有以下两个:

方案1:session复制

既每台服务器上都保存着所有的session信息,该方案采用的是冗余session信息来实现session共享,这种方案在服务器众多时,会有非常大的网络开销。

方案2:session的统一管理实现共享

将多个节点的session统一存放在某个容器中,这个容器推荐使用nosql的redis,因为redis的内存读写快。

3、实现原理

1)通过配置类RedisHttpSessionConfiguration来控制spring-session的参数配置,如session的有效期,redis key的命名空间。

如下:


<property name="redisNamespace" value="weijuju-iag-cmb-service-direct"></property>


2)在启动web容器后,spring会加载实现了WebApplicationInitializer的类,spring-session包提供了AbstractHttpSessionApplicationInitializer实现了WebApplicationInitializer接口。AbstractHttpSessionApplicationInitializer中的onStartup注册了一个DelegatingFilterProxy的过滤器,实际使用了SessionRepositoryFilter。

3)当浏览器请求携带sessionId时,则会将此值保存到redis中。

4)通过session监听器SessionCreatedEvent、SessionDeletedEvent等等监听session创建和移除等事件来得到session的共享机制。

4、使用限制

不支持跨域操作,适用于单点登录。