使用Memcache储存Session

来源:互联网 发布:淘宝等级怎么看 编辑:程序博客网 时间:2024/05/17 08:10

使用Memcache储存Session,用来实现负载均衡环境下Session共享的目的

1.使用MemcacheFilter对请求进行拦截

public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;Cookie cookies[] = request.getCookies();Cookie sCookie = null;String sid = "";if (cookies != null && cookies.length > 0) {for (int i = 0; i < cookies.length; i++) {sCookie = cookies[i];if (sCookie.getName().equals(sessionId)) {sid = sCookie.getValue();}}}if (sid == null || sid.length() == 0) {sid = java.util.UUID.randomUUID().toString();Cookie mycookies = new Cookie(sessionId, sid);mycookies.setMaxAge(-1);if (this.cookieDomain != null && this.cookieDomain.length() > 0) {mycookies.setDomain(this.cookieDomain);}mycookies.setPath(this.cookiePath);response.addCookie(mycookies);}filterChain.doFilter(new HttpServletRequestWrapper(sid, request),servletResponse);}

2.自定义的HttpServletRequestWrapper类

public class HttpServletRequestWrapper extendsjavax.servlet.http.HttpServletRequestWrapper {String sid = "";public HttpServletRequestWrapper(String sid, HttpServletRequest arg0) {super(arg0);this.sid = sid;}public HttpSession getSession(boolean create) {return new HttpSessionSidWrapper(this.sid, super.getSession(create));}public HttpSession getSession() {return new HttpSessionSidWrapper(this.sid, super.getSession());}}

3.自定义的HttpSession类

public HttpSessionSidWrapper(String sid, HttpSession session) {super(session);this.sid = sid;this.map = MemcacheSessionService.getInstance().getSession(sid);<span style="white-space:pre"></span>}

4.使用Memcache客户端连接Memcache服务器,并使用其存储Session对象

public Map<String,Object> getSession(String id) {MemCachedClient mc = this.getMemCachedClient();Object mp = mc.get(id);Map<String,Object> session = null;if (mp == null) {session = new HashMap<String,Object>();mc.set(id, session, new Date(TIME_OUT));//更新session}else {session =(Map<String,Object>)mp;mc.set(id, session, new Date(TIME_OUT));//更新session}return session;}
如何配置MemcacheClient请自行百度


0 0
原创粉丝点击