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();
}
}