Java如何将session保存到redis中呢?

戚薇 Spring 发布时间:2023-07-17 09:38:18 阅读数:6847 1
下文笔者将讲述Spring中session保存到redis中的方法及示例分享
学习完本篇之后,你将彻底掌握session保存到redis中的原理及实现方法
我们都知道session是用于标识用户身份的一个ID
    如今,我们很多服务都采用多节点部署
    当用户访问不同的机器时
    如果没有做session同步,用户就会被退出
    所以我们必须在不同的服务中同步session
	  那么如何实现这一需求呢?下文笔者将讲述将session放入到redis缓存服务器中的方法分享 
=======================================================================================
   让每一个服务验证session是否存在时,去redis服务验证,采用此种方法,可避免session不同步的现象
   那么如何处理这个问题呢?下文笔者将一一道来,如下所示
=======================================================================================
配置过滤器
例:Redis放入到session
一、配置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 = "java265" + 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("java265", 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();
  }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202307/7089.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者