1.引入依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis-session -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
2.配置redis连接
spring:
redis:
host: localhost
port: 6379
database: 1
password:
timeout: 5000ms
3.创建测试controller
@RestController
public class TestController {
//设置参数到session
@GetMapping("/setValue")
public String setValue(String value, HttpServletRequest request){
System.out.println("setValue");
request.getSession().setAttribute("value", value);
return value;
}
//获取session中的参数
@GetMapping("getValue")
public String getValue(HttpServletRequest request){
System.out.println("getValue");
return (String) request.getSession().getAttribute("value");
}
}
4.测试
启动一个8080端口,一个8081端口
从8080端口设置参数,http://localhost:8080/setValue?value=hello
从8081端口获取参数,http://localhost:8081/getValue
可以看出从8081中获取的参数是8080中设置的参数,
因为session保存到redis中了,每次读取session都会从redis中获取,
只要两个项目用的redis是同一个地址同一个索引库,就可以实现集群了
作者公众号
