使用Memcache储存Session
2015-08-12 14:59
537 查看
使用Memcache储存Session,用来实现负载均衡环境下Session共享的目的
1.使用MemcacheFilter对请求进行拦截
2.自定义的HttpServletRequestWrapper类
3.自定义的HttpSession类
4.使用Memcache客户端连接Memcache服务器,并使用其存储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 extends javax.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请自行百度
相关文章推荐
- memcache安装
- Linux下memcache的安装和启动
- memcached windows/linux 安装和启动
- Memcache内存分配策略
- 如何选择redis和memcache
- Memcached真的过时了吗?
- memcached安装及java应用使用memcached
- java使用memcached2--集群部署
- Memcached分布式算法详解
- memcache
- java使用memcached1--安装与基本使用
- memcached学习总结
- 在Linux上安装Memcached服务
- java Memcache使用详解
- 64位window下安装memcache扩展
- Memcache与Redis
- windows下memcached的安装与使用
- ehcache memcache redis 三大缓存男高音
- memcached并发CAS模式
- Redis使用总结之与Memcached异同