Java简单实现session保存到redis的方法示例

本文实例讲述了Java简单实现session保存到redis的方法。分享给大家供大家参考,具体如下:

成都创新互联公司坚持“要么做到,要么别承诺”的工作理念,服务领域包括:做网站、成都网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的博湖网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

负载均衡情况下,如果用户访问不同的机器,如果没有做session同步,用户就会被提出,这样用户体验非常不好,所以我们很有必要做session同步,把session放到reids缓存服务器就能很好的解决问题。下面是代码简单的实现。

一、配置web.xml过滤器:


    sessionFilter
    org.springframework.web.filter.DelegatingFilterProxy


    sessionFilter
    /*


二、配置对应的过滤器名字:


    


三、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 getAttributeNames() {
    final byte[] key = stringSerializer.serialize(sid);
    Object result = redisTemplate.execute(new RedisCallback() {
      @Override
      public Object doInRedis(RedisConnection connection)
          throws DataAccessException {
        Set set = connection.keys(key);
        return set;
      }
    });
    if(result != null) {
      Set s = (Set)result;
      Set ss = new HashSet();
      for(byte[] b : s) {
        ss.add(stringSerializer.deserialize(b));
      }
      Enumeration 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() {
      @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() {
      @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 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程序设计有所帮助。


分享标题:Java简单实现session保存到redis的方法示例
网页URL:http://hbruida.cn/article/gpiddo.html