前提
springboot框架版本
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
1.依赖包
<!-- 引入 spring-session 依赖 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<!-- 引入 springboot 安全框架 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 引入 redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置
spring:
session:
store-type: redis #session 存储类型
redis:
#单节点redis
database: 1
host: 127.0.0.1
port: 6379
3.入口文件
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) # 排除 SecurityAutoConfiguration.class文件,不然会跳到登录页面
@EnableRedisHttpSession //开启使用redis存储session
4. 控制器测试代码
@GetMapping("/setSession")
public Object setSession(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute("userInfo", "new user");
session.setMaxInactiveInterval(3600);
session.getAttribute("userInfo");
return "OK";
}