在分布式系统中,session共享有很多解决方案,其中使用redis缓存是最常用的方案之一
1.想要在springboot用到spring session共享功能,首先需要在springboot项目中添加相关依赖
2.在application.yml添加配置属性
这里为了方便,用同一个项目不同代码编译两次,代码如下
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/testMethod")
public String testMethod(HttpSession session){
logger.info("sessionId={}", session.getId());
logger.info("session中存值");
session.setAttribute("msg", "hello");
return "testMethod";
}
}
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/testMethod")
public String testMethod(HttpSession session){
logger.info("sessionId={}", session.getId());
logger.info("session中取值为{}", session.getAttribute("msg"));
return "testMethod";
}
}
先访问localhost:9988/testMethod
再访问localhost:8811/testMethod
可以看到结果如下
两个项目共享了同一个session!