首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

EhCache 加快你的程序

2013-10-24 
EhCache 加速你的程序ehCache介绍EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate

EhCache 加速你的程序
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下.
Java代码 
<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拦截器检查缓存中是否有用户信息
Java代码 
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
Java代码 
<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" /><!-- 如果不配置或/*,将拦截所有的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下就知道了。

热点排行