问题1:微服务情况下。域名不同。session不共享
问题2:分布式系统下。同一个域名下,多个服务。session会出现不同步问题(例如第一次访问的是A服务,保存了。第二次访问了B,查询到的还是没信息)
解决:1)、session复制(同步)
![](https://i-blog.csdnimg.cn/blog_migrate/f99551c2bdee49f6e4313f72a95a5b50.png)
![](https://i-blog.csdnimg.cn/blog_migrate/d262307bda77d91b44651da619c2c7ea.png)
3)、hash一致行
就是配合负载均衡记录客户端的ip路由到自己访问的服务器(ip求余)
优点
缺点
![](https://i-blog.csdnimg.cn/blog_migrate/3529eafe060fb32dc05b4d431f5a9dcc.png)
4)、统一存储
就是用redis存储
优点:
没有安全隐患
可以水平扩展,一个redis不行就,做多个redis集群
服务器重启也不会有数据丢失
缺点:
增加了一次网络调用,增添代码。远程获取数据,比从内存中获取数据慢
代码就是Map集合存储
总结用SpringSession解决
以上4中解决方法前提都是在同一域名下。
针对不同域名,不同服务,子域session共享
问题就是浏览器在做Cookie的时候会指定域名。源码就是HttpServletResponse 的addCookie方法的setDomain()方法。
response.addCookie(new Cookie("JESSIONID","dada").setDomain(""));
SpringSession核心原理
SessionRepositoryFilter:
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(
request, response, this.servletContext);
SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(
wrappedRequest, response);
try {
filterChain.doFilter(wrappedRequest, wrappedResponse);
}
finally {
wrappedRequest.commitSession();
}
}
SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(request, response, this.servletContext);
包装原始的请求对象:装饰着模式
SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(
wrappedRequest, response);
包装原始的相应对象