亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java簡單實現session保存到redis的方法示例

發布時間:2020-08-31 21:47:38 來源:腳本之家 閱讀:144 作者:ppt0501 欄目:編程語言

本文實例講述了Java簡單實現session保存到redis的方法。分享給大家供大家參考,具體如下:

負載均衡情況下,如果用戶訪問不同的機器,如果沒有做session同步,用戶就會被提出,這樣用戶體驗非常不好,所以我們很有必要做session同步,把session放到reids緩存服務器就能很好的解決問題。下面是代碼簡單的實現。

一、配置web.xml過濾器:

<filter>
    <filter-name>sessionFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>sessionFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

二、配置對應的過濾器名字:

<bean id="sessionFilter" class="com.plateno.interceptor.SessionFilter">
    <property name="redisTemplate" ref="redisTemplate"/>
</bean>

三、SessionFilter的實現:

public class SessionFilter extends GenericFilterBean {
  private RedisTemplate redisTemplate;
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    System.out.println("filter");
    HttpServletRequest re = (HttpServletRequest)request;
    HttpServletResponse res = (HttpServletResponse)response;
    TerryHttpServletRequestWrapper wrapper = new TerryHttpServletRequestWrapper(re,res,redisTemplate);
    chain.doFilter(wrapper, response);
  }
  public RedisTemplate getRedisTemplate() {
    return redisTemplate;
  }
  public void setRedisTemplate(RedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }
}

四、TerryHttpServletRequestWrapper的實現:

public class TerryHttpServletRequestWrapper extends HttpServletRequestWrapper {
  private CacheHttpSession session;
  private HttpServletResponse response;
  private RedisTemplate redisTemplate;
  public TerryHttpServletRequestWrapper(HttpServletRequest request, HttpServletResponse response,RedisTemplate redisTemplate) {
    super(request);
    this.response = response;
    this.redisTemplate = redisTemplate;
  }
  @Override
  public HttpSession getSession(boolean create) {
    if(session != null) {
      return session;
    }
    String sid = "terry" + System.currentTimeMillis();
    writeSidToCookie(sid);
    session = new CacheHttpSession(null,sid,redisTemplate);
    return session;
  }
  @Override
  public HttpSession getSession() {
    return getSession(false);
  }
  protected void writeSidToCookie(String sid) {
    Cookie mycookies = new Cookie("terry", sid);
    mycookies.setMaxAge(-1);
    mycookies.setDomain("locahost");
    mycookies.setPath("/");
    response.addCookie(mycookies);
  }
}

五、CacheHttpSession的實現:

public class CacheHttpSession extends HttpSessionWrapper {
  private String sid;
  private RedisTemplate redisTemplate;
  private StringRedisSerializer stringSerializer = new StringRedisSerializer();
  public CacheHttpSession(HttpSession session,String sid,RedisTemplate redisTemplate) {
    super(session);
    this.sid = sid;
    this.redisTemplate = redisTemplate;
  }
  @SuppressWarnings("unchecked")
  @Override
  public Enumeration<String> getAttributeNames() {
    final byte[] key = stringSerializer.serialize(sid);
    Object result = redisTemplate.execute(new RedisCallback<Object>() {
      @Override
      public Object doInRedis(RedisConnection connection)
          throws DataAccessException {
        Set<byte[]> set = connection.keys(key);
        return set;
      }
    });
    if(result != null) {
      Set<byte[]> s = (Set<byte[]>)result;
      Set<String> ss = new HashSet<String>();
      for(byte[] b : s) {
        ss.add(stringSerializer.deserialize(b));
      }
      Enumeration<String> en = new Vector(ss).elements();
      return en;
    }
    return null;
  }
  @SuppressWarnings("unchecked")
  @Override
  public void setAttribute(String name, Object value) {
    final byte[] key = stringSerializer.serialize(name);
    final byte[] v = stringSerializer.serialize((String)value);
    redisTemplate.execute(new RedisCallback<Object>() {
      @Override
      public Object doInRedis(RedisConnection connection)
          throws DataAccessException {
        connection.set(key, v);
        return null;
      }
    });
  }
  @Override
  public Object getAttribute(String name) {
    final byte[] key = stringSerializer.serialize(name);
    @SuppressWarnings("unchecked")
    Object value = redisTemplate.execute(new RedisCallback<Object>() {
      @Override
      public Object doInRedis(RedisConnection connection)
          throws DataAccessException {
        return connection.get(key);
      }
    });
    return value;
  }
  @Override
  public String getId() {
    return sid;
  }
}

六、HttpSessionWrapper的實現:

public class HttpSessionWrapper implements HttpSession {
  private HttpSession session;
  public HttpSessionWrapper(HttpSession session) {
    this.session = session;
  }
  @Override
  public long getCreationTime() {
    return this.session.getCreationTime();
  }
  @Override
  public String getId() {
    return this.session.getId();
  }
  @Override
  public long getLastAccessedTime() {
    return this.session.getLastAccessedTime();
  }
  @Override
  public ServletContext getServletContext() {
    return this.session.getServletContext();
  }
  @Override
  public void setMaxInactiveInterval(int interval) {
    this.session.setMaxInactiveInterval(interval);
  }
  @Override
  public int getMaxInactiveInterval() {
    return this.session.getMaxInactiveInterval();
  }
  @Override
  public HttpSessionContext getSessionContext() {
    return this.session.getSessionContext();
  }
  @Override
  public Object getAttribute(String name) {
    return this.session.getAttribute(name);
  }
  @Override
  public Object getValue(String name) {
    return this.session.getValue(name);
  }
  @Override
  public Enumeration<String> getAttributeNames() {
    return this.session.getAttributeNames();
  }
  @Override
  public String[] getValueNames() {
    return this.session.getValueNames();
  }
  @Override
  public void setAttribute(String name, Object value) {
    this.session.setAttribute(name,value);
  }
  @Override
  public void putValue(String name, Object value) {
    this.session.putValue(name,value);
  }
  @Override
  public void removeAttribute(String name) {
    this.session.removeAttribute(name);
  }
  @Override
  public void removeValue(String name) {
    this.session.removeValue(name);
  }
  @Override
  public void invalidate() {
    this.session.invalidate();
  }
  @Override
  public boolean isNew() {
    return this.session.isNew();
  }
}

以上代碼就能把session保存到redis,當然這其中還有很多問題,比如sessionId的生成,session過去,對象序列化(測試為了方便統一用了string),等等很多問題。以后有時間再完善。

更多關于java相關內容感興趣的讀者可查看本站專題:《Java+MySQL數據庫程序設計總結》、《Java操作Excel技巧總結》、《Java數據結構與算法教程》、《Java文件與目錄操作技巧匯總》及《Java操作DOM節點技巧總結》

希望本文所述對大家java程序設計有所幫助。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

德惠市| 太仓市| 彭泽县| 青岛市| 东阿县| 景德镇市| 凤山县| 昌邑市| 镇巴县| 南充市| 会东县| 门头沟区| 巫溪县| 都昌县| 宁阳县| 石渠县| 循化| 莱阳市| 延川县| 五莲县| 武山县| 宣武区| 梁河县| 塔城市| 株洲市| 达孜县| 奇台县| 庄浪县| 临汾市| 土默特右旗| 延长县| 海林市| 开鲁县| 禄丰县| 盐城市| 扶沟县| 兴隆县| 萍乡市| 江华| 上高县| 彭阳县|