SpringBoot之基于Redis的Session共享

添加依赖

在pom.xml中添加spring-session-data-redis依赖

1
2
3
4
5
<!-- Session共享 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>

配置

1
2
3
4
5
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60*30)
public class SessionRedisConfig {

}

注意:maxInactiveIntervalInSeconds字段用来设置Session失效时间,使用Redis Session之后,原SpringBoot的server.session.timeout属性不再生效

测试

1
2
3
4
5
6
7
8
9
@RequestMapping("/uid")
public String uid(HttpSession session) {
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid", uid);
return session.getId();
}

将上述配置和代码写入到两个不同的项目中,然后访问http://127.0.0.1:8080/uidhttp://127.0.0.1:8081/uid,返回的sessionId一致:

1
71f3099c-dcc0-4445-8d5e-57ef96d84412

通过Redis客户端连接可以看到:

1
2
3
4
127.0.0.1:6379> keys *
1) "spring:session:sessions:71f3099c-dcc0-4445-8d5e-57ef96d84412"
2) "spring:session:expirations:1531014420000"
3) "spring:session:sessions:expires:71f3099c-dcc0-4445-8d5e-57ef96d84412"