ehCache+spring的简单实用

fmms 12年前

       1、最近在做一个贷款项目是城市分站的 分为贷款前台和贷款机构后台,这个两个平台的二级域名不一样,一个前台是cityname.xx.com,cityname是会地区的不同而变化的,如在 北京就是bj.xx.com,机构后台是loan.xx.com,在机构登录的时候 ,如果把登录信息放在session,会有一个问题,就是当切换到前台的时候,由于域名改变了,此时session就会改变,之前session保存的信 息就不存在了,也就是session跨域问题,最后想到了使用缓存才存储在线用户信息,这样就不存在session跨域的问题。

        2、ehCache介绍

       EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

      下图是 Ehcache 在应用程序中的位置:

       ehCache+spring的简单实用

     

     主要的特性有:

      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)最少使用   -->
③用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;     */         }    }
④将ehcache进行注入的配置applicationContext-ehCache.xml
<beans xmlns="http://www.springframework.org/schema/beans"   xmlns:context="http://www.springframework.org/schema/context"   xmlns:p="http://www.springframework.org/schema/p"   xmlns:mvc="http://www.springframework.org/schema/mvc"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:aop="http://www.springframework.org/schema/aop"   xmlns:tx="http://www.springframework.org/schema/tx"   xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">      <!-- 引用ehCache的配置 -->         <bean id="defaultCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">           <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>
⑤登录的时候,验证用户名密码,正确放入缓存,这里只是提供一个简单的方法(用的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