使用 Spring Session 配合 Redis 管理 HTTP Session
在进行负载均衡时,往往需要处理 Session 同步问题。虽然方案众多且各有缺点,但 Spring Session 通过将 Session 保存到 Redis 来实现同步。无论增加多少个 Tomcat 节点,均无需考虑 Session 问题,且配置非常简单。
1. 添加 Spring Session 依赖
在 pom.xml 中添加以下 Maven 依赖:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
2. 配置 Spring Bean
在 Spring 配置文件中注册 Redis Session 配置类:
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
3. 配置 Web 监听器
在 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>
<>/*

