---
title: "ehCache在acegi中的应用"
author: "bevan58"
date: "2008-12-31T00:29:18Z"
tags: []
slug: "ehcache-acegi"
draft: false
lastmod: "2009-08-22T16:33:33Z"
id: 307404
url: "https://bevan58.iteye.com/blog/307404"
---

转载：[http://blog.chinaunix.net/u2/76927/showart\_1679621.html](http://blog.chinaunix.net/u2/76927/showart_1679621.html)

EhCache一般用途如下：Hibernate缓存，DAO缓存，安全性凭证缓存（Acegi），Web缓存，应用持久化和分布式缓存。

    EhCache在默认情况下，即在用户未提供自身配置文件ehcache.xml或ehcache-failsafe.xml时，EhCache会依据其自身Jar存档包含的ehcache-failsafe.xml文件所定制的策略来管理缓存。如果用户在classpath下提供了ehcache.xml或ehcache-failsafe.xml文件，那么EhCache将会应用这个文件。如果两个文件同时提供，那么EhCache会使用ehcache.xml文件的配置。**EhCache默认内容如下：**

 

`<ehcache>`

`<diskStore path="C:\Acegi6" />    <defaultCache             maxElementsInMemory="10000"             eternal="false"             timeToIdleSeconds="120"             timeToLiveSeconds="120"             overflowToDisk="true"             maxElementsOnDisk="10000000"             diskPersistent="false"             diskExpiryThreadIntervalSeconds="120"             memoryStoreEvictionPolicy="LRU"             /> </ehcache>`

**属性说明：**  
 diskStore：指定数据在磁盘中的存储位置。  
 defaultCache：当借助CacheManager.add("demoCache")创建Cache时，EhCache便会采用&lt;defalutCache/&gt;指定的的管理策略  
**以下属性是必须的：**  
 maxElementsInMemory - 在内存中缓存的element的最大数目  
 maxElementsOnDisk - 在磁盘上缓存的element的最大数目  
 eternal - 设定缓存的elements是否永远不过期。如果为true，则缓存的数据始终有效，如果为false那么还要根据timeToIdleSeconds，timeToLiveSeconds判断  
 overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上  
**以下属性是可选的：**  
 timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时，这些数据便会删除.  
 timeToLiveSeconds - 缓存element的有效生命期  
 diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据，默认是false。  
 diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔，默认是120秒。每个120s，相应的线程会进行一次EhCache中数据的清理工作  
 memoryStoreEvictionPolicy - 当内存缓存达到最大，有新的element加入的时候， 移除缓存中element的策略。默认是LRU（最近最少使用），可选的有LFU（最不常使用）和FIFO（先进先出）

`import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element;    import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;    /**  * 缓存管理器中不存在名为demoCache的缓存，所以需要先添加： * manager.addCache("demoCache");  */ public class EhCacheTestDemo {        protected static final Log log = LogFactory.getLog(EhCacheTestDemo.class);        public static void main(String[] args) {                     CacheManager manager = new CacheManager();         manager.addCache("demoCache");                     String[] cacheNames = manager.getCacheNames();         for (String cacheName : cacheNames) {             log.info("缓存的名字：" + cacheName);         }                     //获得缓存         Cache cache = manager.getCache("demoCache");                     Element element = new Element("data1", "缓存数据1");         //往缓存中存放数据，EhCache会依据一定的策略将数据存储到内存或磁盘中         cache.put(element);         //获得已缓存的数据         log.info(cache.get("data1").getValue());                     element = new Element("data2", "缓存数据2");         cache.put(element);         log.info(cache.get("data2").getValue());                     log.info(cache);         //打印出内存中已缓存的Element数量         log.info(cache.getMemoryStoreSize());         //打印出磁盘中已缓存的Element数量         log.info(cache.getDiskStoreSize());            //将“data1”从缓存中销毁掉         cache.remove("data1");                     log.info(cache.getMemoryStoreSize());         log.info(cache.getDiskStoreSize());            System.exit(-1);     }    }`

如果需要开发着可以提供自身的EhCache缓存配置文件：

`<diskStore path="C:\Acegi6" />`

`<cache name="cacheAcegi"            maxElementsInMemory="1"            maxElementsOnDisk="1000"            eternal="false"            overflowToDisk="true"            timeToIdleSeconds="300"            timeToLiveSeconds="600"            memoryStoreEvictionPolicy="FIFO"             />`

默认放在src目录下，即classpath下面

`import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element;    import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;    /**  * 配置文件中已存在名称为cacheAcegi的缓存，不用添加到缓存管理器中  */ public class EhCacheTestDemoVersion2 {        protected static final Log log = LogFactory.getLog(EhCacheTestDemoVersion2.class);        public static void main(String[] args) {                     CacheManager manager = new CacheManager();                     String[] cacheNames = manager.getCacheNames();         for (String cacheName : cacheNames) {             log.info("缓存的名字：" + cacheName);         }                     //获得缓存         Cache cache = manager.getCache("cacheAcegi");                     Element element = new Element("data1", "缓存数据1");         //往缓存中存放数据，EhCache会依据一定的策略将数据存储到内存或磁盘中         cache.put(element);         //获得已缓存的数据         log.info(cache.get("data1").getValue());                     element = new Element("data2", "缓存数据2");         cache.put(element);         log.info(cache.get("data2").getValue());                     log.info(cache);         //打印出内存中已缓存的Element数量         log.info(cache.getMemoryStoreSize());         //打印出磁盘中已缓存的Element数量         log.info(cache.getDiskStoreSize());            //将“data1”从缓存中销毁掉         cache.remove("data1");                     log.info(cache.getMemoryStoreSize());         log.info(cache.getDiskStoreSize());            System.exit(-1);     }    }`

spring EhCache集成：

`<!-- EhCacheBasedUserCache是EhCache的一个缓存实现，提供了向缓存中放入、取得和删除用户明细信息的功能，Acegi需要用它来管理缓存。 -->     <!-- EhCacheFactoryBean是用于维护Cache实例的工厂Bean，Cache需要依赖于CacheManager而存在 -->    <bean id="userCacheBackend"         class="org.springframework.cache.ehcache.EhCacheFactoryBean">       <property name="cacheManager" ref="cacheManager" />       <property name="cacheName" value="userCache" />缓存名称     </bean>       <!-- 缓存管理器，一个CacheManager能够创建和维护多个Cache实例 -->    <bean id="cacheManager"         class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />`

还可以指定相应的缓存管理策略：

`<bean id="userCacheBackend"         class="org.springframework.cache.ehcache.EhCacheFactoryBean">       <property name="cacheManager" ref="cacheManager" />       <property name="cacheName" value="userCache" />缓存名称`

`<property name="maxElementsInMemory" value="10000" />          .....`

`</bean>`

**Spring EhCache集成引入Acegi：**

      每次当请求一个受保护的资源时，认证管理器就被调用以获取用户的安全信息。但如果获取用户信息涉及到查询数据库，每次都查询相同的数据可能在性能上表现得很糟糕。注意到用户信息不会频繁改变，也许更好的做法是在第一次查询时缓存用户信息，并在后续的查询中直接从缓存中获取用户信息。  
      DaoAuthenticationProvider通过org.acegisecurity.providers.dao.UserCache接口的实现类支持对用户信息进行缓存。  
public interface UserCache {  
    public abstract UserDetails getUserFromCache(String s);  
    public abstract void putUserInCache(UserDetails userdetails);  
    public abstract void removeUserFromCache(String s);  
}

      顾名思义，接口UserCache中方法提供了向缓存中放入、取得和删除用户明细信息的功能。我们可以写一个自己的UserCache实现类，实现对用户信息的缓存。然而，在你考虑开发自己的UserCache实现类之前，应该首先考虑Acegi提供的两个方便的UserCache实现类：  
 org.acegisecurity.providers.dao.cache.NullUserCache  
 org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache

      **NullUserCache**事实上不进行任何缓存。任何时候调用它的getUserFromCache方法，得到的返回值都是null。这是DaoAuthenticationProvider使用的默认UserCache实现。  
public class NullUserCache implements UserCache {  
    public NullUserCache() {}  
    public UserDetails getUserFromCache(String username)  { return null; }  
    public void putUserInCache(UserDetails userdetails) {}  
    public void removeUserFromCache(String s) {}  
}

     **EhCacheBasedUserCache**是一个更实用的缓存实现。类如其名，它是基于开源项目ehcache实现的。ehcache是一个简单快速的针对Java的缓存解决方案，同时也是Hibernate默认的和推荐的缓存方案。

**Acegi配置如下：**

`<bean id="daoAuthenticationProvider"         class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">       ......       <!-- 增加 -->       <property name="userCache"><ref local="userCache"/></property>    </bean>    <!-- EhCacheBasedUserCache是EhCache的一个缓存实现，提供了向缓存中放入、取得和删除用户明细信息的功能，Acegi需要用它来管理缓存。 --> <bean id="userCache" class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">       <property name="cache" ref="userCacheBackend" />    </bean>    <!-- EhCacheFactoryBean是用于维护Cache实例的工厂Bean，Cache需要依赖于CacheManager而存在 -->    <bean id="userCacheBackend"         class="org.springframework.cache.ehcache.EhCacheFactoryBean">       <property name="cacheManager" ref="cacheManager" />       <property name="cacheName" value="userCache" /> 缓存名称      </bean>       <!-- 缓存管理器，一个CacheManager能够创建和维护多个Cache实例 -->    <bean id="cacheManager"         class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />`

EhCache API相关说明：[http://lcllcl987.iteye.com/blog/222693](http://lcllcl987.iteye.com/blog/222693)