1. 程式人生 > >基於redis的session共享實現

基於redis的session共享實現

專案上線,閒來無事,把專案裡用到的session共享貼出來,因為有多個專案要用到這個功能,所以這個部分功能獨立出來了。總得來說,就是自己寫了一個攔截器,在攔截器裡面把session放進了redis裡面,從而實現了session共享。

首先貼出web.xml的配置,和普通攔截器的配置一樣:

<filter>
    <filter-name>sessionFilter</filter-name>
    <filter-class>com.dnkx.web.filter.SessionFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sessionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- session過期時間 -->
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

然後是sessionFilter:
public class SessionFilter extends HttpServlet implements Filter {

    /**
	 * 
	 */
	private static final long serialVersionUID = -5723213015901607291L;

	@Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setAttribute("hostname", InetAddress.getLocalHost().getHostName());

        filterChain.doFilter(new HttpServletRequestWrapper(request, response),
                servletResponse);
    }
}

上面兩段程式碼都是基礎,沒什麼好解釋的,下面貼出關鍵的HttpServletRequestWrapper類:
public class HttpServletRequestWrapper extends
        javax.servlet.http.HttpServletRequestWrapper {

    private static final String cookieId = "csid";
    static String sessionHoldKey = "session_hold_key";

    private String sessionId;

    public HttpServletRequestWrapper(HttpServletRequest request, HttpServletResponse response) {
        super(request);
        sessionIdManage(request, response);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	private void sessionIdManage(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null ) {
           // logger.warn("request.getCookies() returns null,I didn't see it before");
        } else {
            for (int i = 0; i < cookies.length; i++) {
                Cookie sCookie = cookies[i];
                if (sCookie.getName().equals(cookieId)) {
                    sessionId = sCookie.getValue();
                }
            }
        }
        if (sessionId == null || sessionId.length() == 0) {
            sessionIdCreate(response);
        }
        HashOperations hashOps = WebComponentFactory.getSessionRedisTemplate().opsForHash();
        Long lastAccessedTime = (Long) hashOps.get(sessionId, sessionHoldKey);
        long maxInactiveInterval = request.getSession().getMaxInactiveInterval() * 1000;
        if (lastAccessedTime == null || maxInactiveInterval > 0 && System.currentTimeMillis() - lastAccessedTime > maxInactiveInterval) {
            sessionIdCreate(response);
        }
        hashOps.put(sessionId, sessionHoldKey, System.currentTimeMillis());
        WebComponentFactory.getSessionRedisTemplate().expire(sessionId,3, TimeUnit.DAYS);
    }

    private void sessionIdCreate(HttpServletResponse response) {
        sessionId = java.util.UUID.randomUUID().toString();
        Cookie mycookies = new Cookie(cookieId, sessionId);
        mycookies.setPath("/");
        response.addCookie(mycookies);
    }

    public HttpSession getSession(boolean create) {
        return new HttpSessionSidWrapper(this.sessionId, super.getSession(create));
    }

    public HttpSession getSession() {
        return new HttpSessionSidWrapper(this.sessionId, super.getSession());
    }

}

上面這段程式碼是session共享的關鍵部分,這裡需要了解cookie和session的機制,這裡是用一個自己的cookie存了自己生成的sessionId返回給客戶端,每次請求在根據cookie的值來做session的操作,sessionId是存在redis裡面的,根據session做redis的get,set等操作,程式碼也很容易看懂。