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

网友投稿 387 2023-02-05


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()http://;

}

@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.sessPMIYIHdMion.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数据库程序设计总结http://》、《Java操作Excel技巧总结》、《Java数据结构与算法教程》、《Java文件与目录操作技巧汇总》及《Java操作DOM节点技巧总结》

希望本文所述对大家java程序设计有所帮助。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详解node Async/Await 更好的异步编程解决方案
下一篇:Java 日期格式加上指定月数(一个期限)得到一个新日期的实现代码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~