[Java][SpringBoot]集成Redis实现Session共享

159 阅读1分钟

这组版画,太精彩了!_1_国绘画苑_来自小红书网页版.jpg

本文介绍了如何在SpringBoot应用中集成Redis实现Session共享,以解决应用集群部署(或分布式部署)时的Session共享问题。

1 添加相关Maven依赖

<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</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进行配置)

# 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

3 启用RedisHttpSession

在Spring Boot的启动类上添加@EnableRedisHttpSession注解,以启用Redis接管Session。

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的配置覆盖)

A 参考内容