集群环境下的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 ...
随机推荐
- 第六十九天 dom与bom
1.节点 dom与bom属 // DOM:文档对象模型 =>提高给用户操作document obj的标准接口 // DOM:以document为根,树状展开所有子节点 节点分类 // 节点分类: ...
- #!/usr/bin/python3的作用 解决vscode ImportError: No module named xxxx
在 Python 脚本的第一行经常见到这样的注释: #!/usr/bin/env python3 或者 #!/usr/bin/python3 含义 在脚本中, 第一行以 #! 开头的代码, 在计算机行 ...
- Flask 构建微电影视频网站(四)
后台管理 实现后台管理系统使用flask sqlalchemy结合mysql数据库进行增删改查操作.分页的使用.路由装饰器定义.模板中变量调用.登录会话机制.上传文件.flask wtforms表单使 ...
- Magento2 常见错误 ----- 定期更新
1.静态文件有版本号,静态文件不能读取,页面无法显示.如下图: 解决方案:其实URL里的版本号对于magento来说是合法的,这是因为我们缺少了一个文件\pub\static\.htaccess:导致 ...
- [HNOI2016]矿区
[HNOI2016]矿区 平面图转对偶图 方法: 1.分成正反两个单向边,每个边属于一个面 2.每个点按照极角序sort出边 3.枚举每一个边,这个边的nxt就是反边的前一个(这样找到的是面的边逆时针 ...
- Luogu P3227 [HNOI2013]切糕 最小割
首先推荐一个写的很好的题解,个人水平有限只能写流水账,还请见谅. 经典的最小割模型,很多人都说这个题是水题,但我还是被卡了=_= 技巧:加边表示限制 在没有距离\(<=d\)的限制时候,我们对每 ...
- css流式布局
elem{ width:1160px;/*流式布局的总宽度*/ column-width:375px; -moz-column-width: 375px; /*每列宽度*/ -webkit-colum ...
- HTTP和RFC
RFC: Request For Comments(RFC),是一系列以编号排定的文件.文件收集了有关互联网相关信息,以及UNIX和互联网社区的软件文件.目前RFC文件是由Internet Socie ...
- prometheus 基于文件的目标发现
prometheus 基于文件的目标发现 1.创建目录 cd /usr/local/prometheus/conf mkdir -pv targets/{nodes,docker} 2.修改prome ...
- [再寄小读者之数学篇](2014-04-08 from 1297503521@qq.com $\sin x-x\cos x=0$ 的根的估计)
(2014-04-08 from 1297503521@qq.com) 设方程 $\sin x-x\cos x=0$ 在 $(0,+\infty)$ 中的第 $n$ 个解为 $x_n$. 证明: $$ ...