EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现。它支持注解方式使用缓存,非常方便。
可以单独使用,一般在第三方库中被用到的比较多(如mybatis、shiro等)ehcache 对分布式支持不够好,多个节点不能同步,通常和redis一块使用
ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
redis是通过socket访问到缓存服务,效率比ecache低,比数据库要快很多,
处理集群和分布式缓存方便,有成熟的方案。如果是单个应用或者对缓存访问要求很高的应用,用ehcache。如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的,建议用redis。
ehcache也有缓存共享方案,不过是通过RMI或者Jgroup多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适。
1 2 3 4 5 | < dependency > < groupId >net.sf.ehcache</ groupId > < artifactId >ehcache</ artifactId > < version >2.10.2</ version > </ dependency > |
默认情况下Ehcache会自动加载classpath根目录下名为ehcache.xml文件,也可以将该文件放到其他地方在使用时指定文件的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <? xml version = "1.0" encoding = "UTF-8" ?> < ehcache xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation = "http://ehcache.org/ehcache.xsd" > <!-- 磁盘缓存位置 --> < diskStore path = "java.io.tmpdir/ehcache" /> <!-- 默认缓存 --> < defaultCache maxEntriesLocalHeap = "10000" eternal = "false" timeToIdleSeconds = "120" timeToLiveSeconds = "120" maxEntriesLocalDisk = "10000000" diskExpiryThreadIntervalSeconds = "120" memoryStoreEvictionPolicy = "LRU" > < persistence strategy = "localTempSwap" /> </ defaultCache > <!-- helloworld缓存 --> < cache name = "HelloWorldCache" maxElementsInMemory = "1000" eternal = "false" timeToIdleSeconds = "5" timeToLiveSeconds = "5" overflowToDisk = "false" memoryStoreEvictionPolicy = "LRU" /> </ ehcache > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package com.mengdee.manage.cache; import com.mengdee.manage.entity.Dog; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class CacheTest { public static void main(String[] args) { // 1. 创建缓存管理器 CacheManager cacheManager = CacheManager.create( "./src/main/resources/ehcache.xml" ); // 2. 获取缓存对象 Cache cache = cacheManager.getCache( "HelloWorldCache" ); // 3. 创建元素 Element element = new Element( "key1" , "value1" ); // 4. 将元素添加到缓存 cache.put(element); // 5. 获取缓存 Element value = cache.get( "key1" ); System.out.println(value); System.out.println(value.getObjectValue()); // 6. 删除元素 cache.remove( "key1" ); Dog dog = new Dog(1L, "taidi" , ( short ) 2 ); Element element2 = new Element( "taidi" , dog); cache.put(element2); Element value2 = cache.get( "taidi" ); Dog dog2 = (Dog) value2.getObjectValue(); System.out.println(dog2); System.out.println(cache.getSize()); // 7. 刷新缓存 cache.flush(); // 8. 关闭缓存管理器 cacheManager.shutdown(); } } |
diskStore : ehcache支持内存和磁盘两种存储
defaultCache : 默认的缓存
cache :自定的缓存,当自定的配置不满足实际情况时可以通过自定义(可以包含多个cache节点)
name : 缓存的名称,可以通过指定名称获取指定的某个Cache对象
maxElementsInMemory :内存中允许存储的最大的元素个数,0代表无限个
clearOnFlush:内存数量最大时是否清除。
eternal :设置缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。根据存储数据的不同,例如一些静态不变的数据如省市区等可以设置为永不过时
timeToIdleSeconds : 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds :缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
overflowToDisk :内存不足时,是否启用磁盘缓存。
maxEntriesLocalDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
maxElementsOnDisk:硬盘最大缓存个数。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskPersistent:是否在VM重启时存储硬盘的缓存数据。默认值是false。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
1 2 3 4 5 6 | Cache cache = manager.getCache(<span>"mycache"</span>); CacheConfiguration config = cache.getCacheConfiguration(); config.setTimeToIdleSeconds(<span>60</span>); config.setTimeToLiveSeconds(<span>120</span>); config.setmaxEntriesLocalHeap(<span>10000</span>); config.setmaxEntriesLocalDisk(<span>1000000</span>); |
1 | <span>// 可以自己创建一个Cache对象添加到CacheManager中</span> <span>public</span> <span>void</span> <span>addCache</span>(Cache cache); <span>public</span> <span>synchronized</span> <span>void</span> <span>removeCache</span>(String cacheName); |
Cache: 一个Cache可以包含多个Element,并被CacheManager管理。它实现了对缓存的逻辑行为
Element:需要缓存的元素,它维护着一个键值对, 元素也可以设置有效期,0代表无限制
获取CacheManager的方式:
可以通过create()或者newInstance()方法或重载方法来创建获取CacheManager的方式:
1 | <span>public</span> <span>static</span> CacheManager <span>create</span>(); <span>public</span> <span>static</span> CacheManager <span>create</span>(String configurationFileName); <span> public</span> <span>static</span> CacheManager <span>create</span>(InputStream inputStream); <span> public</span> <span>static</span> CacheManager <span>create</span>(URL configurationFileURL); <span>public</span> <span>static</span> CacheManager <span>newInstance</span>(); |
Ehcache的CacheManager构造函数或工厂方法被调用时,会默认加载classpath下名为ehcache.xml的配置文件。
如果加载失败,会加载Ehcache jar包中的ehcache-failsafe.xml文件,这个文件中含有简单的默认配置。
1 2 3 4 5 6 | <span>// CacheManager.create() == CacheManager.create("./src/main/resources/ehcache.xml")</span> <span> // 使用Ehcache默认配置新建一个CacheManager实例</span> CacheManager cacheManager = CacheManager.create(); cacheManager = CacheManager.newInstance(); cacheManager = CacheManager.newInstance(<span>"./src/main/resources/ehcache.xml"</span>); InputStream inputStream = <span>new</span> FileInputStream(<span>new</span> File(<span>"./src/main/resources/ehcache.xml"</span>)); cacheManager = CacheManager.newInstance(inputStream); String[] cacheNames = cacheManager.getCacheNames(); <span> // [HelloWorldCache]</span> |
示例结构:
1 | <span><<span>project</span> <span>xmlns</span>=<span>"http://maven.apache.org/POM/4.0.0"</span> <span> xmlns:xsi</span>=<span>"http://www.w3.org/2001/XMLSchema-instance"</span> <span> xsi:schemaLocation</span>=<span>"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"</span>></span> <span><<span>modelVersion</span>></span>4.0.0<span></<span>modelVersion</span>></span> <span><<span>groupId</span>></span>com.mengdee<span></<span>groupId</span>></span> <span><<span>artifactId</span>></span>ehcache<span></<span>artifactId</span>></span> <span><<span>version</span>></span>0.0.1-SNAPSHOT<span></<span>version</span>></span> <span> <<span>properties</span>></span> <span> <<span>project.build.sourceEncoding</span>></span>UTF-8<span></<span>project.build.sourceEncoding</span>></span> <span> <<span>junit.version</span>></span>4.10<span></<span>junit.version</span>></span> <span><<span>spring.version</span>></span>4.2.3.RELEASE<span></<span>spring.version</span>></span> <span></<span>properties</span>></span> <span> <<span>dependencies</span>></span> <span><<span>dependency</span>></span> <span><<span>groupId</span>></span>junit<span></<span>groupId</span>></span> <span><<span>artifactId</span>></span>junit<span></<span>artifactId</span>></span> <span> <<span>version</span>></span>${junit.version}<span></<span>version</span>></span> <span><<span>scope</span>></span>test<span></<span>scope</span>></span> <span></<span>dependency</span>></span> <span><<span>dependency</span>></span> <span><<span>groupId</span>></span>org.springframework<span></<span>groupId</span>></span> <span><<span>artifactId</span>></span>spring-test<span></<span>artifactId</span>></span> <span><<span>version</span>></span>${spring.version}<span></<span>version</span>></span> <span><<span>scope</span>></span>test<span></<span>scope</span>></span> <span></<span>dependency</span>></span> <span><!-- springframework --></span> <span><<span>dependency</span>></span> <span><<span>groupId</span>></span>org.springframework<span></<span>groupId</span>></span> <span><<span>artifactId</span>></span>spring-webmvc<span></<span>artifactId</span>></span> <span><<span>version</span>></span>${spring.version}<span></<span>version</span>></span> <span></<span>dependency</span>></span> <span><<span>dependency</span>></span> <span><<span>groupId</span>></span>org.springframework<span></<span>groupId</span>></span> <span><<span>artifactId</span>></span>spring-core<span></<span>artifactId</span>></span> <span><<span>version</span>></span>${spring.version}<span></<span>version</span>></span> <span></<span>dependency</span>></span> <span><<span>dependency</span>></span> <span> <<span>groupId</span>></span>org.springframework<span></<span>groupId</span>></span> <span><<span>artifactId</span>></span>spring-context<span></<span>artifactId</span>></span> <span><<span>version</span>></span>${spring.version}<span></<span>version</span>></span> <span></<span>dependency</span>></span> <span><<span>dependency</span>></span> <span><<span>groupId</span>></span>org.springframework<span></<span>groupId</span>></span> <span><<span>artifactId</span>></span>spring-context-support<span></<span>artifactId</span>></span> <span><<span>version</span>></span>${spring.version}<span></<span>version</span>></span> <span></<span>dependency</span>></span> <span><<span>dependency</span>></span> <span><<span>groupId</span>></span>net.sf.ehcache<span></<span>groupId</span>> </span> <span><<span>artifactId</span>></span>ehcache<span></<span>artifactId</span>></span> <span><<span>version</span>></span>2.10.3<span></<span>version</span>></span> <span></<span>dependency</span>></span> <span></<span>dependencies</span>></span> <span><<span>repositories</span>></span> <span><<span>repository</span>></span> <span><<span>id</span>></span>aliyun<span></<span>id</span>></span> <span><<span>name</span>></span>aliyun<span></<span>name</span>></span> <span><<span>url</span>></span>http://maven.aliyun.com/nexus/content/groups/public<span></<span>url</span>></span> <span></<span>repository</span>></span> <span></<span>repositories</span>></span> <span></<span>project</span>></span> |
1 | <span><?xml version="1.0" encoding="UTF-8"?></span> <span><<span>ehcache</span> <span>xmlns:xsi</span>=<span>"http://www.w3.org/2001/XMLSchema-instance"</span> <span>xsi:noNamespaceSchemaLocation</span>=<span>"http://ehcache.org/ehcache.xsd"</span>></span> <span><!-- 磁盘缓存位置 --></span> <span><<span>diskStore</span> <span>path</span>=<span>"java.io.tmpdir/ehcache"</span> /></span> <span><!-- 默认缓存 --></span> <span><<span>defaultCache </span> <span>maxEntriesLocalHeap</span>=<span>"10000"</span> <span>eternal</span>=<span>"false"</span> <span>timeToIdleSeconds</span>=<span>"120"</span> <span>timeToLiveSeconds</span>=<span>"120"</span> <span>maxEntriesLocalDisk</span>=<span>"10000000"</span> <span>diskExpiryThreadIntervalSeconds</span>=<span>"120"</span> <span>memoryStoreEvictionPolicy</span>=<span>"LRU"</span>></span> <span><<span>persistence</span> <span>strategy</span>=<span>"localTempSwap"</span>/></span> <span></<span>defaultCache</span>></span> <span><!-- helloworld缓存 --></span> <span><<span>cache</span> <span>name</span>=<span>"HelloWorldCache"</span> <span>maxElementsInMemory</span>=<span>"1000"</span> <span>eternal</span>=<span>"false"</span> <span>timeToIdleSeconds</span>=<span>"5"</span> <span>timeToLiveSeconds</span>=<span>"5"</span> <span>overflowToDisk</span>=<span>"false"</span> <span>memoryStoreEvictionPolicy</span>=<span>"LRU"</span>/></span> <span><<span>cache</span> <span>name</span>=<span>"UserCache"</span> <span>maxElementsInMemory</span>=<span>"1000"</span> <span>eternal</span>=<span>"false"</span> <span>timeToIdleSeconds</span>=<span>"1800"</span> <span>timeToLiveSeconds</span>=<span>"1800"</span> <span>overflowToDisk</span>=<span>"false"</span> <span>memoryStoreEvictionPolicy</span>=<span>"LRU"</span>/></span> <span></<span>ehcache</span>></span> |
spring-base.xml
1 | <span><?xml version="1.0" encoding="UTF-8"?></span> <span><<span>beans</span> <span>xmlns</span>=<span>"http://www.springframework.org/schema/beans"</span> <span>xmlns:xsi</span>=<span>"http://www.w3.org/2001/XMLSchema-instance"</span> <span>xmlns:context</span>=<span>"http://www.springframework.org/schema/context"</span> <span>xmlns:util</span>=<span>"http://www.springframework.org/schema/util"</span> <span>xsi:schemaLocation</span>=<span>"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"</span>></span> <span><<span>context:component-scan</span> <span>base-package</span>=<span>"com.mengdee.**.dao,com.mengdee.**.service"</span>/></span> <span></<span>beans</span>></span> |
spring-ehcache.xml
1 | <span><?xml version="1.0" encoding="UTF-8"?></span> <span><<span>beans</span> <span>xmlns</span>=<span>"http://www.springframework.org/schema/beans"</span> <span>xmlns:xsi</span>=<span>"http://www.w3.org/2001/XMLSchema-instance"</span> <span>xmlns:cache</span>=<span>"http://www.springframework.org/schema/cache"</span> <span>xsi:schemaLocation</span>=<span>"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"</span>></span> <span><<span>description</span>></span>ehcache缓存配置管理文件<span></<span>description</span>></span> <span><!-- 启用缓存注解开关 --></span> <span><<span>cache:annotation-driven</span> <span>cache-manager</span>=<span>"cacheManager"</span>/></span> <span><<span>bean</span> <span>id</span>=<span>"cacheManager"</span> <span>class</span>=<span>"org.springframework.cache.ehcache.EhCacheCacheManager"</span>></span> <span><<span>property</span> <span>name</span>=<span>"cacheManager"</span> <span>ref</span>=<span>"ehcache"</span>/></span> <span></<span>bean</span>></span> <span><<span>bean</span> <span>id</span>=<span>"ehcache"</span> <span>class</span>=<span>"org.springframework.cache.ehcache.EhCacheManagerFactoryBean"</span>></span> <span><<span>property</span> <span>name</span>=<span>"configLocation"</span> <span>value</span>=<span>"classpath:ehcache.xml"</span>/></span> <span></<span>bean</span>></span> <span></<span>beans</span>></span> |
EhcacheService
1 2 | <span>package</span> com.mengdee.manager.service; <span>import</span> com.mengdee.manager.entity.User; <span>public</span> <span><span>interface</span> <span>EhcacheService</span> {</span> <span>// 测试失效情况,有效期为5秒</span> <span>public</span> String <span>getTimestamp</span>(String param); <span>public</span> String <span>getDataFromDB</span>(String key); <span>public</span> <span>void</span> <span>removeDataAtDB</span>(String key); <span>public</span> String <span>refreshData</span>(String key); <span>public</span> User <span>findById</span>(String userId); <span>public</span> <span>boolean</span> <span>isReserved</span>(String userId); <span>public</span> <span>void</span> <span>removeUser</span>(String userId); <span>public</span> <span>void</span> <span>removeAllUser</span>(); } |
EhcacheServiceImpl:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <span>package</span> com.mengdee.manager.service; <span>import</span> org.springframework.cache.annotation.CacheEvict; <span>import</span> org.springframework.cache.annotation.CachePut; <span>import</span> org.springframework.cache.annotation.Cacheable; <span>import</span> org.springframework.stereotype.Service; <span>import</span> com.mengdee.manager.entity.User; <span>@Service</span> <span>public</span> <span><span>class</span> <span>EhcacheServiceImpl</span> <span>implements</span> <span>EhcacheService</span>{</span> <span>// value的值和ehcache.xml中的配置保持一致</span> <span>@Cacheable</span>(value=<span>"HelloWorldCache"</span>, key=<span>"#param"</span>) <span>@Override</span> <span>public</span> String <span>getTimestamp</span>(String param) { Long timestamp = System.currentTimeMillis(); <span>return</span> timestamp.toString(); } <span>@Cacheable</span>(value=<span>"HelloWorldCache"</span>, key=<span>"#key"</span>) <span>@Override</span> <span>public</span> String <span>getDataFromDB</span>(String key) { System.out.println(<span>"从数据库中获取数据..."</span>); <span>return</span> key + <span>":"</span> + String.valueOf(Math.round(Math.random()*<span>1000000</span>)); } <span>@CacheEvict</span>(value=<span>"HelloWorldCache"</span>, key=<span>"#key"</span>) <span>@Override</span> <span>public</span> <span>void</span> <span>removeDataAtDB</span>(String key) { System.out.println(<span>"从数据库中删除数据"</span>); } <span>@CachePut</span>(value=<span>"HelloWorldCache"</span>, key=<span>"#key"</span>) <span>@Override</span> <span>public</span> String <span>refreshData</span>(String key) { System.out.println(<span>"模拟从数据库中加载数据"</span>); <span>return</span> key + <span>"::"</span> + String.valueOf(Math.round(Math.random()*<span>1000000</span>)); } <span>// ------------------------------------------------------------------------</span> <span>@Cacheable</span>(value=<span>"UserCache"</span>, key=<span>"'user:' + #userId"</span>) <span>public</span> User <span>findById</span>(String userId) { System.out.println(<span>"模拟从数据库中查询数据"</span>); <span>return</span> (User) <span>new</span> User(<span>"1"</span>, <span>"mengdee"</span>); } <span>@Cacheable</span>(value=<span>"UserCache"</span>, condition=<span>"#userId.length()<12"</span>) <span>public</span> <span>boolean</span> <span>isReserved</span>(String userId) { System.out.println(<span>"UserCache:"</span>+userId); <span>return</span> <span>false</span>; } <span>//清除掉UserCache中某个指定key的缓存 </span> <span>@CacheEvict</span>(value=<span>"UserCache"</span>,key=<span>"'user:' + #userId"</span>) <span>public</span> <span>void</span> <span>removeUser</span>(String userId) { System.out.println(<span>"UserCache remove:"</span>+ userId); } <span>//清除掉UserCache中全部的缓存 </span> <span>@CacheEvict</span>(value=<span>"UserCache"</span>, allEntries=<span>true</span>) <span>public</span> <span>void</span> <span>removeAllUser</span>() { System.out.println(<span>"UserCache delete all"</span>); } } |
Spring对缓存的支持类似于对事务的支持。
首先使用注解标记方法,相当于定义了切点,然后使用Aop技术在这个方法的调用前、调用后获取方法的入参和返回值,进而实现了缓存的逻辑。
@Cacheable
表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。
这个注解可以用condition属性来设置条件,如果不满足条件,就不使用缓存能力,直接执行方法。
可以使用key属性来指定key的生成规则。
@Cacheable 支持如下几个参数:
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL,如果要引用参数值使用井号加参数名,如:#userId,
一般来说,我们的更新操作只需要刷新缓存中某一个值,所以定义缓存的key值的方式就很重要,最好是能够唯一,因为这样可以准确的清除掉特定的缓存,而不会影响到其它缓存值 ,
本例子中使用实体加冒号再加ID组合成键的名称,如”user:1”、”order:223123”等
1 2 3 4 | <span>// 将缓存保存到名称为UserCache中,键为"user:"字符串加上userId值,如 'user:1'</span> <span>@Cacheable</span>(value=<span>"UserCache"</span>, key=<span>"'user:' + #userId"</span>) <span>public</span> User <span>findById</span>(String userId) { <span>return</span> (User) <span>new</span> User(<span>"1"</span>, <span>"mengdee"</span>); } <span>// 将缓存保存进UserCache中,并当参数userId的长度小于12时才保存进缓存,默认使用参数值及类型作为缓存的key</span> <span>// 保存缓存需要指定key,value, value的数据类型,不指定key默认和参数名一样如:"1"</span> <span>@Cacheable</span>(value=<span>"UserCache"</span>, condition=<span>"#userId.length() < 12"</span>) <span>public</span> <span>boolean</span> <span>isReserved</span>(String userId) { System.out.println(<span>"UserCache:"</span>+userId); <span>return</span> <span>false</span>; } |
@CachePut
与@Cacheable不同,@CachePut不仅会缓存方法的结果,还会执行方法的代码段。它支持的属性和用法都与@Cacheable一致。
@CacheEvict
与@Cacheable功能相反,@CacheEvict表明所修饰的方法是用来删除失效或无用的缓存数据。
@CacheEvict 支持如下几个参数:
1 2 3 4 5 | <span>//清除掉UserCache中某个指定key的缓存 </span> <span>@CacheEvict</span>(value=<span>"UserCache"</span>,key=<span>"'user:' + #userId"</span>) <span>public</span> <span>void</span> <span>removeUser</span>(User user) { System.out.println(<span>"UserCache"</span>+user.getUserId()); } <span>//清除掉UserCache中全部的缓存 </span> <span>@CacheEvict</span>(value=<span>"UserCache"</span>, allEntries=<span>true</span>) <span>public</span> <span>final</span> <span>void</span> <span>setReservedUsers</span>(String[] reservedUsers) { System.out.println(<span>"UserCache deleteall"</span>); } |
SpringTestCase
1 | <span>package</span> com.mengdee.manager; <span>import</span> org.junit.runner.RunWith; <span>import</span> org.springframework.test.context.ContextConfiguration; <span>import</span> org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; <span>import</span> org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <span>@ContextConfiguration</span>(locations = {<span>"classpath:conf/spring/spring-*.xml"</span>}) <span>@RunWith</span>(SpringJUnit4ClassRunner.class) <span>public</span> <span><span>class</span> <span>SpringTestCase</span> <span>extends</span> <span>AbstractJUnit4SpringContextTests</span>{</span> } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <span>package</span> com.mengdee.manager; <span>import</span> org.junit.Test; <span>import</span> org.springframework.beans.factory.annotation.Autowired; <span>import</span> com.mengdee.manager.service.EhcacheService; <span>public</span> <span><span>class</span> <span>EhcacheServiceTest</span> <span>extends</span> <span>SpringTestCase</span>{</span> <span>@Autowired</span> <span>private</span> EhcacheService ehcacheService; <span>// 有效时间是5秒,第一次和第二次获取的值是一样的,因第三次是5秒之后所以会获取新的值</span> <span>@Test</span> <span>public</span> <span>void</span> <span>testTimestamp</span>() <span>throws</span> InterruptedException{ System.out.println(<span>"第一次调用:"</span> + ehcacheService.getTimestamp(<span>"param"</span>)); Thread.sleep(<span>2000</span>); System.out.println(<span>"2秒之后调用:"</span> + ehcacheService.getTimestamp(<span>"param"</span>)); Thread.sleep(<span>4000</span>); System.out.println(<span>"再过4秒之后调用:"</span> + ehcacheService.getTimestamp(<span>"param"</span>)); } <span>@Test</span> <span>public</span> <span>void</span> <span>testCache</span>(){ String key = <span>"zhangsan"</span>; String value = ehcacheService.getDataFromDB(key); <span>// 从数据库中获取数据...</span> ehcacheService.getDataFromDB(key); <span>// 从缓存中获取数据,所以不执行该方法体</span> ehcacheService.removeDataAtDB(key); <span>// 从数据库中删除数据</span> ehcacheService.getDataFromDB(key); <span>// 从数据库中获取数据...(缓存数据删除了,所以要重新获取,执行方法体)</span> } <span>@Test</span> <span>public</span> <span>void</span> <span>testPut</span>(){ String key = <span>"mengdee"</span>; ehcacheService.refreshData(key); <span>// 模拟从数据库中加载数据</span> String data = ehcacheService.getDataFromDB(key); System.out.println(<span>"data:"</span> + data); <span>// data:mengdee::103385</span> ehcacheService.refreshData(key); <span>// 模拟从数据库中加载数据</span> String data2 = ehcacheService.getDataFromDB(key); System.out.println(<span>"data2:"</span> + data2); <span>// data2:mengdee::180538 </span> } <span>@Test</span> <span>public</span> <span>void</span> <span>testFindById</span>(){ ehcacheService.findById(<span>"1"</span>); <span>// 模拟从数据库中查询数据</span> ehcacheService.findById(<span>"1"</span>); } <span>@Test</span> <span>public</span> <span>void</span> <span>testIsReserved</span>(){ ehcacheService.isReserved(<span>"123"</span>); ehcacheService.isReserved(<span>"123"</span>); } <span>@Test</span> <span>public</span> <span>void</span> <span>testRemoveUser</span>(){ <span>// 线添加到缓存</span> ehcacheService.findById(<span>"1"</span>); <span>// 再删除</span> ehcacheService.removeUser(<span>"1"</span>); <span>// 如果不存在会执行方法体</span> ehcacheService.findById(<span>"1"</span>); } <span>@Test</span> <span>public</span> <span>void</span> <span>testRemoveAllUser</span>(){ ehcacheService.findById(<span>"1"</span>); ehcacheService.findById(<span>"2"</span>); ehcacheService.removeAllUser(); ehcacheService.findById(<span>"1"</span>); ehcacheService.findById(<span>"2"</span>); <span>// 模拟从数据库中查询数据</span> <span>// 模拟从数据库中查询数据</span> <span>// UserCache delete all</span> <span>// 模拟从数据库中查询数据</span> <span>// 模拟从数据库中查询数据</span> } } |
示例Demo代码下载:http://download.csdn.net/detail/vbirdbest/9852783
参考文章: http://www.cnblogs.com/jingmoxukong/p/5975994.html