欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-17 08:06:40
本文实例讲述了java简单实现session保存到redis的方法。分享给大家供大家参考,具体如下: 在负载均衡情况下,如果用户访问不同的机器,如果没有做session同...

本文实例讲述了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程序设计有所帮助。

上一篇:

下一篇: