官方文档:
https://docs.spring.io/spring-session/docs/2.2.0.RELEASE/reference/html5/
支持的存储介质
-
Redis
-
MongoDB
-
JDBC
实现原理
-
通过HttpServletRequest定制HttpSession对象
-
调用org.springframework.session.web.http.SessionRepositoryFilter#doFilterInternal方法进行HttpSession对象的定制处理;
-
调用org.springframework.session.web.http.SessionRepositoryFilter.SessionRepositoryRequestWrapper#getSession(boolean)方法从存储介质中获取session;
-
调用org.springframework.session.web.http.SessionRepositoryFilter.SessionRepositoryRequestWrapper#commitSession方法把session信息存储到存储介质中;
-
基于Redis实现Spring Session
引入依赖
-
spring-session-data-redis
-
spring-boot-starter-data-redis
基本配置
-
使用@EnableRedisHttpSession注解
-
提供RedisConnectionFactory(SpringBoot可以不需要这步)
-
实现AbstractHttpSessionApplicationInitializer(SpringBoot可以不需要这步)
SpringBoot的yml配置
-
spring.session.store-type=redis(指定存储介质)
-
spring.session.timeout=
-
spring.redis.host=
-
spring.redis.port=
-
……
代码示例
@SpringBootApplication
@EnableRedisHttpSession
public class TraceBackApplication {
public static void main(String[] args) {
SpringApplication.run(TraceBackApplication.class, args);
}
}
pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
yml配置
spring:
session:
store-type: redis
timeout: 3600s
使用Session
@GetMapping("/test")
public ResponseEntity testSession(HttpSession session, String value) {
String sessionValue = (String) session.getAttribute("test");
if (StringUtils.isEmpty(sessionValue)) {
session.setAttribute("test", value);
sessionValue = value;
}
return ResponseEntity.ok(sessionValue);
}