您好,登錄后才能下訂單哦!
本文實例講述了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程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。