本文介绍了如何在SpringBoot应用中集成Redis实现Session共享,以解决应用集群部署(或分布式部署)时的Session共享问题。
1 添加相关Maven依赖
xml
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lettuce redis连接池需引入commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- spring session redis 用于实现session共享 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
2 添加Redis配置
如应用已集成redis,可跳过此步骤。
在application.properties
配置文件中添加redis配置: (本文redis为集群部署,可根据自身redis进行配置)
properties
# redis密码
spring.redis.password=redis@password123
# 集群节点
spring.redis.cluster.nodes=7.201.11.221:6379,7.201.11.222:6379,7.201.11.223:6379,7.201.11.224:6379,7.201.11.225:6379,7.201.11.226:6379
spring.redis.cluster.max-redirects=3
# 集群拓扑自适应刷新
spring.redis.lettuce.cluster.refresh.adaptive=true
# 集群拓扑定时刷新周期,单位:毫秒
spring.redis.lettuce.cluster.refresh.period=30000
# 开启连接池
spring.redis.lettuce.pool.enabled=true
3 启用RedisHttpSession
在Spring Boot的启动类上添加@EnableRedisHttpSession注解,以启用Redis接管Session。
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@SpringBootApplication
// 启用Redis接管Session,maxInactiveIntervalInSeconds设置session过期时间
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600 * 24 * 7)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4 Session过期时间配置
在@EnableRedisHttpSession
注解中的maxInactiveIntervalInSeconds
属性用于配置Session过期时间,单位为秒。
如@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600 * 24 * 7)
代表过期时间为7天。
注意:启用RedisHttpSession后,原有的session超时配置
server.servlet.session.timeout
会失效(被@EnableRedisHttpSession的配置覆盖)