This article describes the simple implementation of Java session saving to redis. Share it for your reference, as follows:
In load balancing, if the user accesses a different machine and does not perform session synchronization, the user will be asked, which is very bad for the user experience, so it is very necessary for us to perform session synchronization. Put the session on the reids cache server can solve the problem well. The following is a simple implementation of the code.
1. Configure the web.xml filter:
<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>
2. Configure the corresponding filter name:
<bean id="sessionFilter"> <property name="redisTemplate" ref="redisTemplate"/></bean>
Implementation of 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; }}4. Implementation of 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.redisTemplate = 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); }}5. Implementation of 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; }}6. Implementation of 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(); }}The above code can save the session to redis. Of course, there are many problems, such as the generation of sessionId, the past session, object serialization (testing uses string for convenience), and many other problems. I will improve it later if I have time.
For more information about Java related content, please check out the topics of this site: "Java+MySQL database programming summary", "Java operation Excel skills summary", "Java data structure and algorithm tutorial", "Java file and directory operation skills summary" and "Java operation DOM node skills summary"
I hope this article will be helpful to everyone's Java programming.