ehCache工具类:
package com.trustel.common; import java.net.URL; import java.util.List; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * ehCache工具类 * @author bxw * */ public class EhcacheUtil { private static final String path = "/ehcache.xml"; private URL url; private CacheManager manager; private static EhcacheUtil ehCache; private EhcacheUtil(String path) { url = getClass().getResource(path); manager = CacheManager.create(url); } public static EhcacheUtil getInstance() { if (ehCache== null) { ehCache= new EhcacheUtil(path); } return ehCache; } /** * create cache(不会过期) * @param name * @return */ public Cache createCache(String name) { Cache cache = new Cache(name, 10000, false, true, Integer.MAX_VALUE, Integer.MAX_VALUE); manager.addCache(cache); return manager.getCache(name); } /** * 返回cache的size * @param cache * @return */ public int getcacheSize(Cache cache){ List<String> keys = cache.getKeys(); for(String key:keys){ cache.get(key); } return cache.getSize(); } /** * 在已知cache中添加键值对(element级别上设置过期时间) * @param cacheName cache名称 * @param key 键 * @param value 值 * @param time element 要添加的元素 */ public void put(String cacheName, String key, Object value,boolean eternal,int time) { Cache cache = manager.getCache(cacheName); Element element = new Element(key, value); element.setEternal(eternal); element.setTimeToLive(time); cache.put(element); } /** * 获得已知cache的键值对 * @param cacheName cache名称 * @param key 键 * @return */ public Object get(String cacheName, String key) { Cache cache = manager.getCache(cacheName); Element element = cache.get(key); return element == null ? null : element.getObjectValue(); } /** * 获得已知cache * @param cacheName * @return */ public Cache get(String cacheName) { return manager.getCache(cacheName); } /** * 移除已知cache的键值对 * @param cacheName * @param key */ public void remove(String cacheName, String key) { Cache cache = manager.getCache(cacheName); cache.remove(key); } }
配置文件ehcache.xml放在根目录下:
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> <defaultCache eternal="false" maxElementsInMemory="10000" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU"/> <cache name="iap_all_dept_name" eternal="false" maxElementsInMemory="10000" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU"/> <cache name="sys_param" eternal="false" maxElementsInMemory="10000" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU"/> </ehcache>
缓存配置
name:缓存名称。
maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
-->
===================分界线======================
使用spring整合EhCache:
绑定Ehcache
org.springframework.cache.ehcache.EhCacheManagerFactoryBean:
加载Ehcache配置文件。org.springframework.cache.ehcache.EhCacheCacheManager
:支持net.sf.ehcache.CacheManager。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"> <description>ehcache缓存配置管理文件</description> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache/ehcache.xml"/> </bean> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcache"/> </bean> <!-- 启用缓存注解开关 --> <cache:annotation-driven cache-manager="cacheManager"/> </beans>
使用Spring的缓存注解
开启注解
Spring为缓存功能提供了注解功能,但是你必须启动注解。
你有两个选择:
(1) 在xml中声明
像上一节spring-ehcache.xml中的做法一样,使用<cache:annotation-driven/>
<cache:annotation-driven cache-manager="cacheManager"/>
(2) 使用标记注解
你也可以通过对一个类进行注解修饰的方式在这个类中使用缓存注解。
范例如下:
@Configuration
@EnableCaching
public class AppConfig {
}
注解基本使用方法
Spring对缓存的支持类似于对事务的支持。
首先使用注解标记方法,相当于定义了切点,然后使用Aop技术在这个方法的调用前、调用后获取方法的入参和返回值,进而实现了缓存的逻辑。
下面三个注解都是方法级别:
@Cacheable
表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。
这个注解可以用condition
属性来设置条件,如果不满足条件,就不使用缓存能力,直接执行方法。
可以使用key
属性来指定key的生成规则。
@CachePut
与@Cacheable
不同,@CachePut
不仅会缓存方法的结果,还会执行方法的代码段。
它支持的属性和用法都与@Cacheable
一致。
@CacheEvict
与@Cacheable
功能相反,@CacheEvict
表明所修饰的方法是用来删除失效或无用的缓存数据。
下面是@Cacheable
、@CacheEvict
和@CachePut
基本使用方法的一个集中展示:
@Service public class UserService { // @Cacheable可以设置多个缓存,形式如:@Cacheable({"books", "isbns"}) @Cacheable({"users"}) public User findUser(User user) { return findUserInDB(user.getId()); } @Cacheable(value = "users", condition = "#user.getId() <= 2") public User findUserInLimit(User user) { return findUserInDB(user.getId()); } @CachePut(value = "users", key = "#user.getId()") public void updateUser(User user) { updateUserInDB(user); } @CacheEvict(value = "users") public void removeUser(User user) { removeUserInDB(user.getId()); } @CacheEvict(value = "users", allEntries = true) public void clear() { removeAllInDB(); } }
@Caching
如果需要使用同一个缓存注解(@Cacheable
、@CacheEvict
或@CachePut
)多次修饰一个方法,就需要用到@Caching
。
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)
@CacheConfig
与前面的缓存注解不同,这是一个类级别的注解。
如果类的所有操作都是缓存操作,你可以使用@CacheConfig
来指定类,省去一些配置。
@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {
@Cacheable
public Book findBook(ISBN isbn) {...}
}
详细参考:http://blog.csdn.net/poorcoder_/article/details/55258253