spring session redis实现会话共享
点关注不迷路,欢迎再访!
精简博客内容,尽量已行业术语来分享。
努力做到对每一位认可自己的读者负责。
帮助别人的同时更是丰富自己的良机。
一.前言介绍
spring session通过redis来实现多个服务器间的session共享的原理,其实就是将session独立出来不依赖原来的web容器,而是存放到与web容器没有耦合关系的redis容器中,这样即使是任何一台web容器挂了,也不会影响到其中的session,如下图所示:
spring session在spring框架中的实现原理,其实就是在请求request上通过DelegatingFilterProxy代理过滤器封装了一层,将原来存储在容器缓存的session变成存储在redis的session,所以在web.xml中的此filter必须得是在所有filter的前面。
二.引入依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
三.实现代码
1.xml注入方式
<bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="180"></property>
<property name="configureRedisAction" value="NO_OP"></property>
</bean>
2.配置类方式
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3*60)
public class SessionConfig {
//让Spring Session不再执行config命令
@Bean
public ConfigureRedisAction configureRedisAction(){
return ConfigureRedisAction.NO_OP;
}
}
注意,用了spring session后,在web.xml设置的session过期时间是无效。因为此session已经不是原来的存储在容器缓存内的session了,而是被封装多了一层后存储在redis的session。
四.配置过滤器
注意:排字符过滤器后
<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>
五.验证环节
分别启动两台服务,查看session是否一致
redis客户端上查看session