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