一、 目前无非就是三种单机Session(基于单机内存,无法部署多台机器)、基于Cookie(安全性差)、基于全局的统一Session管理(redis、mysql)等多种方式 ;
二、
采用的是redis进行集中式Session管理,核心依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
三、application.yml 配置
server:
port: 8080
spring:
redis:
database: 1
host: localhost
pool:
max-active: 20
开启@EnableRedisHttpSession
server:
port: 8080
spring:
redis:
database: 1
host: localhost
pool:
max-active: 20
开启@EnableRedisHttpSession
通过加上@EnableRedisHttpSession
注解,开启redis集中式session管理,所有的session都存放到了redis中
@SpringBootApplication
@EnableRedisHttpSession
public class AppApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(AppApplication.class, args);
}
}
server:
port: 8080
spring:
redis:
database: 1
host: localhost
pool:
max-active: 20
开启@EnableRedisHttpSession
通过源码可知、可以通过设置maxInactiveIntervalInSeconds来设定session的统一过期时间,
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ java.lang.annotation.ElementType.TYPE })
@Documented
@Import(RedisHttpSessionConfiguration.class)
@Configuration
public @interface EnableRedisHttpSession {
int maxInactiveIntervalInSeconds() default 1800;
String redisNamespace() default "";
RedisFlushMode redisFlushMode() default RedisFlushMode.ON_SAVE;
}
通过redis集中式管理session这种方式在使用上面对客户端是透明的,无需自己操作redis,在使用HttpSession对象的时候直接使用即可
@RestController
public class IndexController {
@GetMapping("/index")
public ResponseEntity index(HttpSession httpSession) {
httpSession.setAttribute("user", "helloword");
return ResponseEntity.ok("ok");
}
@GetMapping("/helloword")
public ResponseEntity hello(HttpSession httpSession) {
return ResponseEntity.ok(httpSession.getAttribute("user"));
}
}
server:
port: 8080
spring:
redis:
database: 1
host: localhost
pool:
max-active: 20
开启@EnableRedisHttpSession