1. 保证Redis启动
2. 导入依赖
SpringBoot+Spring-Session+Redis
<!--spring boot 与redis应用基本环境配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency> <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3. 配置大配置文件application.yml
server:
#port: 8080 port: 8081 #redis配置 spring: redis: database: 0 host: 127.0.0.1 port: 6379 # password: redis
controller
@RestController public class SessionController { //存放Session值 @RequestMapping("/setSession") public String setSession(HttpServletRequest request){ request.getSession().setAttribute("username","zhangsan"); return "success"; } //获取Session值 @RequestMapping("/getSession") public String getSession(HttpServletRequest request){ return (String)request.getSession().getAttribute("username"); } }
在当前项目同时启动8080和8081端口
在8080端口set数据
正常get数据
此时set的session已被保存到redis
8081端口访问时检测自己有没有,
没有的话从redis取出
同样可以正常访问
redis