集群环境下的Session共享

1 //定义请求经过的Session过滤器
public class SessionFilter extends OncePerRequestFilter implements Filter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 从cookie中获取sessionId,如果此次请求没有sessionId,重写为这次请求设置一个sessionId
String sid = CookieUtil.getCookieValue(request, GlobalConstant.JSESSIONID);
if (StringUtils.isEmpty(sid) || sid.length() != 36) {
sid = UUID.randomUUID().toString();
CookieUtil.setCookie(request, response, GlobalConstant.JSESSIONID, sid, 60 * 60);
}
// 交给自定义的HttpServletRequestWrapper处理
filterChain.doFilter(new HttpServletRequestWrapper(sid, request, response), response);
}
}
//Cookie
public static void setCookie(HttpServletRequest request,
HttpServletResponse response, String name, String value, int seconds) {
if (StringUtils.isEmpty(name) || StringUtils.isEmpty(value))
return;
Cookie cookie = new Cookie(name, value);
//cookie.setDomain(domain);
cookie.setMaxAge(seconds);
cookie.setPath("/");
response.setHeader("P3P",
"CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'");
response.addCookie(cookie);
} public String getCookieValue(String name)
throws UnsupportedEncodingException {
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (name.equalsIgnoreCase(cookies[i].getName())) {
return cookies[i].getValue();
}
}
}
return "";
}
//SessionService实现 sidKey == sessionID+SessionKey
public Object getSession(String sidKey) {
Object realValue = null;
try {
String key = “SESSION_DISTRIBUTED_SESSIONID” + sidKey;
realValue = SerializeUtil.unserialize(RedisUtils.getInstance().get(key.getBytes()));
} catch (Exception e) {
LOG.error("Redis获取session异常" + e.getMessage(), e.getCause());
}
return realValue;
} public void saveSession(String sidKey, Object value) {
try {
String key = “SESSION_DISTRIBUTED_SESSIONID” + sidKey;
boolean isSetSuccess = RedisUtils.getInstance().set(key.getBytes(), SerializeUtil.serialize(value));
if (!isSetSuccess) {
LOG.error("Redis保存session异常");
}
} catch (Exception e) {
LOG.error("Redis保存session异常" + e.getMessage(), e.getCause());
}
} public void removeSession(String sidKey) {
try {
String key =“SESSION_DISTRIBUTED_SESSIONID”+ sidKey;
RedisUtils.getInstance().del(key.getBytes());
} catch (Exception e) {
LOG.error("Redis删除session的attribute异常" + e.getMessage(), e.getCause());
}
} public void removeAllSession(String sid) {
try {
String keyPattern =“SESSION_DISTRIBUTED_SESSIONID” + sid + "*";
Set<byte[]> keys = RedisUtils.getInstance().keys(keyPattern.getBytes());
for (byte[] key : keys) {
RedisUtils.getInstance().del(key);
}
} catch (Exception e) {
LOG.error("Redis删除session异常" + e.getMessage(), e.getCause());
}
} public Set<String> getAllKeys(String sid) {
try {
Set<String> keysResult = new HashSet<String>();
String keyPattern =“SESSION_DISTRIBUTED_SESSIONID” + sid + "*";
Set<byte[]> keys = RedisUtils.getInstance().keys(keyPattern.getBytes()); for (byte[] key : keys) {
keysResult.add(new String(key));
}
return keysResult;
} catch (Exception e) {
LOG.error("Redis删除session异常" + e.getMessage(), e.getCause());
return null;
}
}
HttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper
private HttpSession session; private HttpServletRequest request; private HttpServletResponse response; private String sid = ""; public HttpServletRequestWrapper(HttpServletRequest request) {
super(request);
} public HttpServletRequestWrapper(String sid, HttpServletRequest request) {
super(request);
this.sid = sid;
} public HttpServletRequestWrapper(String sid, HttpServletRequest request, HttpServletResponse response) {
super(request);
this.request = request;
this.response = response;
this.sid = sid;
if (this.session == null) {
this.session = new HttpSessionWrapper(sid, super.getSession(false), request, response);
}
} @Override
public HttpSession getSession(boolean create) {
if (this.session == null) {
if (create) {
this.session = new HttpSessionWrapper(this.sid, super.getSession(create), this.request, this.response);
return this.session;
} else {
return null;
}
}
return this.session;
} @Override
public HttpSession getSession() {
if (this.session == null) {
this.session = new HttpSessionWrapper(this.sid, super.getSession(), this.request, this.response);
}
return this.session;
}
HttpSessionWrapper implements HttpSession{ private String sid = ""; private HttpSession session; private HttpServletRequest request; private HttpServletResponse response; private SessionService sessionService = (SessionService) SpringContextHolder.getBean("sessionService"); public HttpSessionWrapper() {
} public HttpSessionWrapper(HttpSession session) {
this.session = session;
} public HttpSessionWrapper(String sid, HttpSession session) {
this(session);
this.sid = sid;
} public HttpSessionWrapper(String sid, HttpSession session,
HttpServletRequest request, HttpServletResponse response) {
this(sid, session);
this.request = request;
this.response = response;
} @Override
public Object getAttribute(String name) {
return sessionService.getSession(this.sid+"#"+name);
} @Override
public void setAttribute(String name, Object value) {
sessionService.saveSession(this.sid+"#"+name, value);
} @Override
public void invalidate() {
sessionService.removeAllSession(this.sid);
CookieUtil.removeCookieValue(this.request,this.response, GlobalConstant.JSESSIONID);
} @Override
public void removeAttribute(String name) {
sessionService.removeSession(this.sid+"#"+name);
} @Override
public Object getValue(String name) {
return this.session.getValue(name);
} @SuppressWarnings("unchecked")
@Override
public Enumeration getAttributeNames() {
return (new Enumerator(sessionService.getAllKeys(this.sid), true));
} @Override
public String getId() {
return this.sid;
}
69 }
集群环境下的Session共享的更多相关文章
- 集群环境下,Session管理的几种手段
集群环境下,Session管理的几种手段 1.Session复制 缺点:集群服务器间需要大量的通信进行Session复制,占用服务器和网络的大量资源. 由于所有用户的Session信息在每台服务器上都 ...
- weblogic 12C集群环境下的session复制
做过weblogic集群环境的人应该都清楚,要想实现session同步,必须满足两个条件:第一,在weblogic.xml里面增加session同步相关的代码:第二,所有放入session的类都要序列 ...
- 集群环境下的Session管理
1. 集群环境下的管理HTTPSSession所遇到的问题 一台服务器对应这个一个session对象,无法在另外一个服务器互通 解决方法: 1. Session 的 Replication(复制)将当 ...
- nginx+php负载均衡集群环境中的session共享方案梳理
在网站使用nginx+php做负载均衡情况下,同一个IP访问同一个页面会被分配到不同的服务器上,如果session不同步的话,就会出现很多问题,比如说最常见的登录状态. 下面罗列几种nginx负载均衡 ...
- 【原创】Tomcat集群环境下对session进行外部缓存的方法(2)
Session对象的持久化比较麻烦,虽然有序列化,但是并不确定Session对象中保存的其他信息是否可以序列化,这可能是网上很多解决方案摒弃此种做法的原因,网上的很多做法都是将Session中的att ...
- 【原创】Tomcat集群环境下对session进行外部缓存的方法(1)
BJJC网改版, 计划将应用部署在tomcat集群上,集群的部署方案为Apache+Tomcat6,连接件为mod_jk,其中开启了session复制和粘性session.计划节点数为3个. 到这,或 ...
- 集群环境下Shiro Session的管理
问题引入 紧接上篇连接 在多台tomcat集群中,shiro管理的session需要放在Redis中,我们只需要增加redisSessionDAO的配置就行 <!-- 定义会话管理器的操作 表示 ...
- Shiro权限管理框架(二):Shiro结合Redis实现分布式环境下的Session共享
首发地址:https://www.guitu18.com/post/2019/07/28/44.html 本篇是Shiro系列第二篇,使用Shiro基于Redis实现分布式环境下的Session共享. ...
- redis 与java的连接 和集群环境下Session管理
redis 的安装与设置开机自启(https://www.cnblogs.com/zhulina-917/p/11746993.html) 第一步: a) 搭建环境 引入 jedis jar包 co ...
随机推荐
- NOI2018游记
Day-1 下午报道,没什么好说的 Day0 先考笔试,开幕式咕到了下午 笔试没什么好说的,反正都是 \(100\) 好像有很多人被gedit坑了? 下午开幕式,很多省的口号都有意思,比如: &quo ...
- python 高阶函数之 reduce
1.正常写法 >>> from functools import reduce >>> def fn(x, y): ... return x * 10 + y .. ...
- MT【315】勾股数
(高考压轴题)证明以下命题:(1)对任意正整数$a$都存在正整数$b,c(b<c)$,使得$a^2,b^2,c^2$成等差数列.(2)存在无穷多个互不相似的三角形$\Delta_n$,其边长$a ...
- bzoj5028小Z的加油店(线段树+差分)
题意:维护支持以下两种操作的序列:1 l r询问a[l...r]的gcd,2 l r x把a[l...r]全部+x 题解:一道经典题.根据gcd(a,b)=gcd(a-b,b)以及区间加可知,这题可以 ...
- java正则表达式取出匹配字符串
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public s ...
- ArrayList的实现及原理
ArrayList ArrayList是最常见以及每个Java开发者最熟悉的集合类了,顾名思义,ArrayList就是一个以数组形式实现的集合,以一张表格来看一下ArrayList里面有哪些基本的元素 ...
- kubernetes云平台管理实战: 集群部署(一)
一.环境规划 1.架构拓扑图 2.主机规划 3.软件版本 [root@k8s-master ~]# cat /etc/redhat-release CentOS Linux release 7.4.1 ...
- kubernetes云平台管理实战: pod资源共享(三)
一.共享容器IP地址 1.查看容器进程 [root@k8s-node1 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS ...
- Entity Framework入门教程(13)---EF中的高并发
EF中的高并发 这里只介绍EF6中database-first开发方案的高并发解决方案,code-first开发方案中的高并发会在以后的EF CodeFirst系列中介绍. EF默认支持乐观并发:我们 ...
- LFYZ-OJ ID: 1028 背包问题
背包问题 题目描述 简单的背包问题.设有一个背包,可以放入的重量为s.现有n件物品,重量分别为w1,w2-,wn,(1≤i≤n)均为正整数,从n件物品中挑选若干件,使得放入背包的重量之和正好为s.找到 ...