最开始的想法是使用session监听器,在session创建时,根据sessionid为键,map为值,加入redis中.,在session销毁时删除此sessionid.
包装session,重写session中的方法来设置值和取得值.
包装request,将包装的session作为包装request的session.
结果在实现时,发现每次创建session时id都不同而且控制不了,这样的话一台服务器死掉,切换到另一台服务器的时候
原来存在redis中的数据得不到.
后面又想覆盖掉jsessionid,没成功.只能创建了一个rsessionid来做,在过滤器中根据此键来存入redis,
由于关闭ofbiz时,session销毁没有执行,只能设置存活时间.
由于有多个组件要使用此功能那么在初始化连接时初始一次就行了.
不过目前为止还没有上线,不知道这样有没有问题.
主要代码:
public void init(FilterConfig arg0) throws ServletException { if (redisClient == null) { synchronized (RedisFilter.class) { if (redisClient == null) { redisClient = RedisClient.getRedisClient(); } } } } //当关闭服务器时session销毁没有触发session监听器 PRivate void setRedisAttribute(String id) { Jedis redis = null; try { redis = redisClient.getJedis(); Object redisValue = redis.get(UtilObject.getBytes(id)); if (redisValue == null) { synchronized (RedisFilter.class) { if (redisValue == null) { redis.set(UtilObject.getBytes(id), UtilObject.getBytes(new HashMap<String, Object>())); redis.expire(UtilObject.getBytes(id), 86400); } } } } catch (Exception e) { e.printStackTrace(); } finally { redisClient.returnJedis(redis); } }HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; Cookie[] cookies = request.getCookies(); String sessionId = "", cookiePath = ""; int maxAge = -1; if (cookies != null) { for (Cookie c : cookies) { if (c.getName().equals("RSESSIONID")) { sessionId = c.getValue(); cookiePath = c.getPath(); maxAge = c.getMaxAge(); } } } HttpSession session = request.getSession(); sessionId = UtilValidate.isEmpty(sessionId) ? session.getId() : sessionId; cookiePath = "/"; session.setAttribute("redisSessionId", sessionId); Cookie c1 = new Cookie("RSESSIONID", sessionId); c1.setPath(cookiePath); response.addCookie(c1); arg2.doFilter(request, response);
新闻热点
疑难解答