服务器之家

服务器之家 > 正文

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

时间:2021-04-28 11:44     来源/作者:ppt0501

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

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

一、配置web.xml过滤器:

?
1
2
3
4
5
6
7
8
<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>

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

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

三、SessionFilter的实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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的实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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的实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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的实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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程序设计有所帮助。

原文链接:https://blog.csdn.net/ppt0501/article/details/46700221

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
返回顶部