3.1、在pom.xml中引入依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2</version>
</dependency>
3.2、在src/main/resources/创建一个配置文件 ehcache.xml
![复制代码](https://i-blog.csdnimg.cn/blog_migrate/9fafc5631ba1215db74dcb775c5144aa.png)
<?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>
![复制代码](https://i-blog.csdnimg.cn/blog_migrate/9fafc5631ba1215db74dcb775c5144aa.png)
3.3、测试类
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 | import 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. 创建缓存管理器,这个时候要去类路径下找到ehcache,然后完成ehcach.xml的加载 URL resource = CacheMain.class.getClassLoader().getResource("ehcache.xml"); CacheManager cacheManager = CacheManager.create( resource); // 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: " + value); System.out.println(value.getObjectValue()); // 6. 删除元素 cache.remove( "key1" ); Dog dog = new Dog( "xiaohei" , "black" , 2 ); Element element2 = new Element( "dog" , dog); cache.put(element2); Element value2 = cache.get( "dog" ); System.out.println( "value2: " + value2); Dog dog2 = (Dog) value2.getObjectValue(); System.out.println(dog2); System.out.println(cache.getSize()); // 7. 刷新缓存 cache.flush(); // 8. 关闭缓存管理器 cacheManager.shutdown(); } } |
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 | public class Dog { private String name; private String color; private int age; public Dog() { } public Dog(String name, String color, int age) { super (); this .name = name; this .color = color; this .age = age; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getColor() { return color; } public void setColor(String color) { this .color = color; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } @Override public String toString() { return "Dog [name=" + name + ", color=" + color + ", age=" + age + "]" ; } } |