使用Memcache储存Session

使用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 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请自行百度


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值