Spring-session+Redis解决Session共享

时间:2023-12-25 13:16:37

   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: #redis配置
spring:
redis:
database:
host: 127.0.0.1
port:
# 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数据

Spring-session+Redis解决Session共享

正常get数据

Spring-session+Redis解决Session共享

此时set的session已被保存到redis

8081端口访问时检测自己有没有,

没有的话从redis取出

同样可以正常访问

Spring-session+Redis解决Session共享

redis

Spring-session+Redis解决Session共享