在Web项目中配置Spring Session分为四步:
借助像Maven或Gradle这样的依赖管理器,将Spring Session添加应用中是很容易的。
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.3.0.RELEASE</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>biz.paluch.redis</groupId>
<artifactId>lettuce</artifactId>
<version>3.5.0.Final</version>
</dependency>
进行配置前,需要先安装redis,然后基于redis进行一系列的配置。Linux下的redis安装教程:Linux下redis安装和部署 ,windows下直接官网下载,运行即可。 添加了必要的依赖之后,我们需要创建相应的Spring配置。Spring配置是要创建一个Servlet过滤器,它用Spring Session支持的HttpSession实现来替换容器本身HttpSession实现。这一步也是Spring Session的核心。(注意:需添加对应的xml声明文件)
<!-- 创建名为 springSessionRepositoryFilter 的Spring Bean,继承自Filter。
springSessionRepositoryFilter替换容器默认的HttpSession支持为Spring Session,
将Session实例存放在Redis中 -->
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<!-- 使用LettuceConnectionFactory -->
<bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory">
<property name="hostName" value="127.0.0.1"/>
<property name="port" value="6379"/>
</bean>
<!-- 让Spring Session不再执行config命令 -->
<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
在web.xml中加入以下过滤器,注意如果web.xml中有其他过滤器,一般情况下Spring 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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
参考文章: 使用Spring Session和Redis解决分布式Session跨域共享问题