ehCache+spring的簡單實用
1、最近在做一個貸款項目是城市分站的 分為貸款前臺和貸款機構后臺,這個兩個平臺的二級域名不一樣,一個前臺是cityname.xx.com,cityname是會地區的不同而變化的,如在 北京就是bj.xx.com,機構后臺是loan.xx.com,在機構登錄的時候 ,如果把登錄信息放在session,會有一個問題,就是當切換到前臺的時候,由于域名改變了,此時session就會改變,之前session保存的信 息就不存在了,也就是session跨域問題,最后想到了使用緩存才存儲在線用戶信息,這樣就不存在session跨域的問題。
2、ehCache介紹
EhCache 是一個純Java的進程內緩存框架,具有快速、精干等特點,是Hibernate中默認的CacheProvider。
下圖是 Ehcache 在應用程序中的位置:
主要的特性有:
1. 快速.2. 簡單.
3. 多種緩存策略
4. 緩存數據有兩級:內存和磁盤,因此無需擔心容量問題
5. 緩存數據會在虛擬機重啟的過程中寫入磁盤
6. 可以通過RMI、可插入API等方式進行分布式緩存
7. 具有緩存和緩存管理器的偵聽接口
8. 支持多緩存管理器實例,以及一個實例的多個緩存區域
9. 提供Hibernate的緩存實現
下面說ehcache的使用
①下載??????ehcache.jar,自己去google下載地址
②隨后,開始配置ehCache的屬性,ehCache需要一個xml文件來設置ehCache相關的一些屬性,如最大緩存數量、cache刷新的時間等等
??ehcache.xml放在你的classpath下.<ehcache> <!--<diskStore path="c:\myapp\cache"/> --><defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" />
<cache name="DEFAULT_CACHE" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000" overflowToDisk="false" /> </ehcache> <!-- 1.必須要有的屬性: name: cache的名字,用來識別不同的cache,必須惟一。 maxElementsInMemory: 內存管理的緩存元素數量最大限值。 maxElementsOnDisk: 硬盤管理的緩存元素數量最大限值。默認值為0,就是沒有限制。 eternal: 設定元素是否持久話。若設為true,則緩存元素不會過期。 overflowToDisk: 設定是否在內存填滿的時候把數據轉到磁盤上。 2.下面是一些可選屬性: timeToIdleSeconds: 設定元素在過期前空閑狀態的時間,只對非持久性緩存對象有效。默認值為0,值為0意味著元素可以閑置至無限長時間。 timeToLiveSeconds: 設定元素從創建到過期的時間。其他與timeToIdleSeconds類似。 diskPersistent: 設定在虛擬機重啟時是否進行磁盤存儲,默認為false.(我的直覺,對于安全小型應用,宜設為true)。 diskExpiryThreadIntervalSeconds: 訪問磁盤線程活動時間。 diskSpoolBufferSizeMB: 存入磁盤時的緩沖區大小,默認30MB,每個緩存都有自己的緩沖區。 memoryStoreEvictionPolicy: 元素逐出緩存規則。共有三種,Recently Used (LRU)最近最少使用,為默認。 First In First Out (FIFO),先進先出。Less Frequently Used(specified as LFU)最少使用 --></pre>③用spring3攔截器檢查緩存中是否有用戶信息
package com.woaika.loan.front.common.filter;import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
import net.sf.ehcache.Cache; import net.sf.ehcache.Element;
import org.apache.log4j.Logger; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
import com.woaika.loan.front.loanuser.vo.LoginOrganVo; import com.woaika.loan.ip.IPUtil; import com.woaika.loan.po.LoanOrgan;
public class OrgMgtInterceptor implements HandlerInterceptor {
private Logger log = Logger.getLogger(OrgMgtInterceptor.class); private Cache ehCache; @Resource(name="ehCache") public void setEhCache(Cache ehCache) { this.ehCache = ehCache; } public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { //log.info("==============執行順序: 3、afterCompletion================"); } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { //log.info("==============執行順序: 2、postHandle================"); } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // log.info("==============執行順序: 1、preHandle================"); String ip = IPUtil.getRemortIP(request); Element elementIp = ehCache.get(ip); if(null==elementIp){ response.sendRedirect(com.woaika.loan.commons.constants.SiteConstant.JIGOU_URL+"/tologin"); return false; }else{ LoginOrganVo vo =(LoginOrganVo)elementIp.getObjectValue(); if(vo!=null){ Element elementId = ehCache.get(vo.getId().toString()); if(elementId!=null){ String tempIp = (String)elementId.getObjectValue(); if(tempIp!=null && !"".equals(tempIp) && ip.equals(tempIp)){ request.setAttribute("currentOrgan", vo); return true; } }else{ response.sendRedirect(com.woaika.loan.commons.constants.SiteConstant.JIGOU_URL+"/tologin"); return false; } } } return true; /* String url=request.getRequestURL().toString(); // if(url.matches(mappingURL)){ HttpSession session = request.getSession(); LoanOrgan org = (LoanOrgan)session.getAttribute("currentOrgan"); if(org!=null){ return true; }else{ response.sendRedirect(com.woaika.loan.commons.constants.SiteConstant.JIGOU_URL+"/tologin"); } return false; // } // return true; */ }
}</pre>④將ehcache進行注入的配置applicationContext-ehCache.xml
<beans xmlns=" <property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean><!-- 定義ehCache的工廠,并設置所使用的Cache name --> <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <ref local="defaultCacheManager"/> </property> <property name="cacheName"> <value>DEFAULT_CACHE</value> </property> </bean>
</beans></pre>⑤登錄的時候,驗證用戶名密碼,正確放入緩存,這里只是提供一個簡單的方法(用的spring的mvc)
@RequestMapping(value="/login") public String login(String organname, String pwd, HttpServletRequest request, HttpServletResponse response){ judgmentCity.getCityInfo(request); LoanOrgan organ = loanOrganService.login(organname, pwd); if(organ==null){ request.setAttribute("msg", "用戶名或密碼錯誤"); return "forward:/jigou/tologin"; }else{ //將機構信息存在cache中,來進行跨域 String ip = IPUtil.getRemortIP(request); LoginOrganVo vo = new LoginOrganVo(); vo.setId(organ.getId()); vo.setOrganname(organ.getOrganname()); Element elementip = new Element(ip, (Serializable) vo); Element elementid = new Element(organ.getId().toString(), ip); //Element elementvo = new Element(organ.getId().toString(), (Serializable) vo); ehCache.put(elementip);//添加到緩存 ehCache.put(elementid); // ehCache.put(elementvo); //request.getSession().setAttribute("currentOrgan", organ); return "redirect:/organmgt/index"; } }注銷操作(用的spring的mvc)://注銷登錄 @RequestMapping(value="/logout") public String logout(HttpServletRequest request){ String ip = IPUtil.getRemortIP(request); Element elementIp = ehCache.get(ip); if(elementIp!=null){ LoginOrganVo vo =(LoginOrganVo)elementIp.getObjectValue(); if(vo!=null){ ehCache.remove(vo.getId()); } } ehCache.remove(ip); //request.getSession().removeAttribute("currentOrgan"); return "redirect:/jigou/tologin"; }⑥spring3攔截器的配置文件<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/organmgt/**" /><!-- 如果不配置或/*,將攔截所有的Controller --> <bean class="com.woaika.loan.front.common.filter.OrgMgtInterceptor"> </bean> </mvc:interceptor> </mvc:interceptors>這樣所有的/organmgt/開頭的請求都會被攔截,在這個攔截器進行檢查是否登錄就可以,這里我采用的是用戶客戶端ip和用戶id兩個key存儲了用戶信息保證用戶的唯一信。
事實上到了這里,一個簡單的Spring + ehCache Framework基本完成了。這里并沒有說太多的spring ioc和基于注釋的注入,我向大家google一下就會很多,mvc我用的spring的mvc ,網上也是很多,google下就知道了。
轉自:http://blog.csdn.net/ajun_studio/article/details/7267777