ste1 . 引入依赖
<!-- Ehcache核心包 -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.6.1</version>
</dependency>
ste2 . 创建xml ,并定义缓存器
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">
<!-- 通过xml 定义缓存容器名称 -->
<cache alias="helloCache">
<!-- 定义缓存数据key类型 -->
<key-type>java.lang.Long</key-type>
<!-- 定义缓存数据value类型 -->
<value-type>java.lang.String</value-type>
<!-- 定义当前缓存容器堆大小 -->
<resources>
<!--最大存10个键值对 -->
<heap unit="entries">10</heap>
</resources>
</cache>
</config>
ste3 . 通过xml 创建缓存管理器 CacheManager
package com.cn.java.base.ehcache;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;
import java.net.URL;
public class TestXml {
public static void main(String[] args) {
URL url = TestXml.class.getResource("/cache/ehcache.xml");
XmlConfiguration configuration = new XmlConfiguration(url);
/** step : 1 通过xml配置创建 缓存管理器cacheManager */
CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
/** step : 2 初始化管理器 */
cacheManager.init();
/** step : 3 从缓存容器中 取出定义的容器 */
Cache<Long, String> cache = cacheManager.getCache("helloCache", Long.class, String.class);
cache.put(1L, "Say Ehcache!");
String value = cache.get(1L);
System.out.println("<<<<<<< <<"+value);
/** step : 4 使用完后关闭缓存 */
cacheManager.close();
}
}