一. maven添加Ehcache的依赖jar包:
<!--ehcache 相关包 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.7.5</version> </dependency> <dependency> <groupId>com.googlecode.ehcache-spring-annotations</groupId> <artifactId>ehcache-spring-annotations</artifactId> <version>1.2.0</version> </depenency>
二. 项目中创建ehcache.xml文件,配置cache的相关信息:
<?xml version="1.0" encoding="UTF-8"?> <ehcache updateCheck="false"> <!-- 磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存 path:指定在硬盘上存储对象的路径 --> <!--<diskStore path="java.io.tmpdir"/>--> <diskStore path="E:\\cache"/> <!-- Cluster localhost setting --> <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446, timeToLive=32"/> <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="hostName=localhost, port=40001,socketTimeoutMillis=2000"/> <!-- maxElementsInMemory设置成1,overflowToDisk设置成true,只要有一个缓存元素,就直接存到硬盘上去 eternal设置成true,代表对象永久有效 maxElementsOnDisk设置成0 表示硬盘中最大缓存对象数无限大 diskPersistent设置成true表示缓存虚拟机重启期数据 --> <!--根据需要配置自定义cache--> <cache name="dictCache" maxElementsInMemory="1" overflowToDisk="true" eternal="true"> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties="replicatePuts=false,replicateUpdatesViaCopy=false"/> </cache> <!--根据需要配置自定义cache--> <cache name="eternalCache" maxElementsInMemory="100" overflowToDisk="true" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200"> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties="replicatePuts=false,replicateUpdatesViaCopy=false"/> </cache> <!-- DefaultCache setting. Modify ehcache-safe.xml for timeToIdleSeconds,timeToLiveSecond,diskExpiryThreadIntervalSeconds Use ehcache-safe.xml default for maxElementsInMemory,maxElementsOnDisk,overflowToDisk,eternal Use ehcache default for memoryStoreEvictionPolicy,diskPersistent,. --> <!-- defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理 maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象 eternal:代表对象是否永不过期 overflowToDisk:当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中 --> <defaultCache maxElementsInMemory="10000" overflowToDisk="true" eternal="false" memoryStoreEvictionPolicy="LRU" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="600" timeToIdleSeconds="3600" timeToLiveSeconds="100000" diskPersistent="false"/> </ehcache>
三. Spring管理ehcache相关配置,spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"> <!-- 自动扫描包--> <!--数据源配置信息--> <!--事物管理配置--> <!--方式一: 注解方式配置--> <cache:annotation-driven cache-manager="cacheManager" /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcache"></property> </bean> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml"></property> </bean> <!--方式二:通过CacheManager方式--> </beans>
实例:
//新增 /** 使用注解时,value值对应ehcache.xml中caache的name */ //@Cacheable(value = "dictCache", key = "'test_' + '#entity.getId'") public Serializable save(TestDemoEntity entity) throws Exception{ //通过 CacheManager创建cache对象 CacheManager cacheManager = CacheManager.getInstance(); //getCache(param),param参数对应ehcache.xml文件中cache的name的值 Cache dictCache = cacheManager.getCache("dictCache"); //通过Element对象设置要存储的key=value Element element = new Element(key,value); dictCache.put(element); List keys = dictCache.getKeys(); Serializable t = super.save(entity); this.doAddBus(entity); return t; }
//删除 //@CacheEvict(value = "dictCache",key = "'test_' + '#entity.getId'") public void delete(TestDemoEntity entity) throws Exception{ CacheManager cacheManager = CacheManager.getInstance(); Cache dictCache = cacheManager.getCache("dictCache"); //判断要删除的key是否在缓存中 if(dictCache.isElementInMemory(key)){ dictCache.remove(key); } super.delete(entity); this.doDelBus(entity); }
//获取cache中keys public void getCacheKeys() throws Exception{ CacheManager cacheManager = CacheManager.getInstance(); Cache dictCache = cacheManager.getCache("dictCache"); //查询cache中所有的key List list = dictCache.getKeys(); //查询cache中key的数量 Integer count = dictCache.getSize(); }
//根据key获取value private void getValue(String key) throws Exception{ CacheManager cacheManager = CacheManager.getInstance(); Cache dictCache = cacheManaher.getCache("dictCache"); //通过get(key)方法获取到的是Element对象 Element element = dictCache.get(key); //element获取value有两种方式 //第一种:获取到的vlaue的类型时Serializable Serializable value = element.getValue(); //第二种:获取到的value的类型为Object Object obj = element.getObjectValue(); }