什麼是ehCache
EhCache 是一個純Java的進程內緩存框架,具有快速、精幹等特點,是Hibernate中默認的CacheProvider。
一、具體描述
Ehcache是一個用Java實現的使用簡單,高速,實現線程安全的緩存管理類庫,ehcache提供了用內存,磁盤文件存儲,以及分佈式存儲方式等多種靈活的cache管理方案。同時ehcache作爲開放源代碼項目,採用限制比較寬鬆的Apache License V2.0作爲授權方式,被廣泛地用於Hibernate, Spring,Cocoon等其他開源系統。Ehcache 從 Hibernate 發展而來,逐漸涵蓋了 Cahce 界的全部功能,是目前發展勢頭最好的一個項目。具有快速,簡單,低消耗,依賴性小,擴展性強,支持對象或序列化緩存,支持緩存或元素的失效,提供 LRU、LFU 和 FIFO 緩存策略,支持內存緩存和磁盤緩存,分佈式緩存機制等等特點。
下圖是 Ehcache 在應用程序中的位置:
二、主要特性
快速、簡單;
多種緩存策略;
緩存數據有兩級:內存和磁盤,因此無需擔心容量問題;
緩存數據會在虛擬機重啓的過程中寫入磁盤;
可以通過 RMI、可插入 API 等方式進行分佈式緩存;
具有緩存和緩存管理器的偵聽接口;
支持多緩存管理器實例,以及一個實例的多個緩存區域;
提供 Hibernate 的緩存實現;
配置ehcache.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!-- 磁盤緩存位置 -->
<diskStore path="java.io.tmpdir"/>
<!-- 默認緩存 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- 測試 -->
<cache name="userCache"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU">
</cache>
</ehcache>
<!--<diskStore>==========當內存緩存中對象數量超過maxElementsInMemory時,將緩存對象寫到磁盤緩存中(需對象實現序列化接口) -->
<!--<diskStore path="">==用來配置磁盤緩存使用的物理路徑,Ehcache磁盤緩存使用的文件後綴名是*.data和*.index -->
<!--name=================緩存名稱,cache的唯一標識(ehcache會把這個cache放到HashMap裏) -->
<!--maxElementsOnDisk====磁盤緩存中最多可以存放的元素數量,0表示無窮大 -->
<!--maxElementsInMemory==內存緩存中最多可以存放的元素數量,若放入Cache中的元素超過這個數值,則有以下兩種情況 -->
<!--1)若overflowToDisk=true,則會將Cache中多出的元素放入磁盤文件中 -->
<!--2)若overflowToDisk=false,則根據memoryStoreEvictionPolicy策略替換Cache中原有的元素 -->
<!--eternal==============緩存中對象是否永久有效,即是否永駐內存,true時將忽略timeToIdleSeconds和timeToLiveSeconds -->
<!--timeToIdleSeconds====緩存數據在失效前的允許閒置時間(單位:秒),僅當eternal=false時使用,默認值是0表示可閒置時間無窮大,此爲可選屬性 -->
<!--即訪問這個cache中元素的最大間隔時間,若超過這個時間沒有訪問此Cache中的某個元素,那麼此元素將被從Cache中清除 -->
<!--timeToLiveSeconds====緩存數據在失效前的允許存活時間(單位:秒),僅當eternal=false時使用,默認值是0表示可存活時間無窮大 -->
<!--即Cache中的某元素從創建到清楚的生存時間,也就是說從創建開始計時,當超過這個時間時,此元素將從Cache中清除 -->
<!--overflowToDisk=======內存不足時,是否啓用磁盤緩存(即內存中對象數量達到maxElementsInMemory時,Ehcache會將對象寫到磁盤中) -->
<!--會根據標籤中path值查找對應的屬性值,寫入磁盤的文件會放在path文件夾下,文件的名稱是cache的名稱,後綴名是data -->
<!--diskPersistent=======是否持久化磁盤緩存,當這個屬性的值爲true時,系統在初始化時會在磁盤中查找文件名爲cache名稱,後綴名爲index的文件 -->
<!--這個文件中存放了已經持久化在磁盤中的cache的index,找到後會把cache加載到內存 -->
<!--要想把cache真正持久化到磁盤,寫程序時注意執行net.sf.ehcache.Cache.put(Element element)後要調用flush()方法 -->
<!--diskExpiryThreadIntervalSeconds==磁盤緩存的清理線程運行間隔,默認是120秒 -->
<!--diskSpoolBufferSizeMB============設置DiskStore(磁盤緩存)的緩存區大小,默認是30MB -->
<!--memoryStoreEvictionPolicy========內存存儲與釋放策略,即達到maxElementsInMemory限制時,Ehcache會根據指定策略清理內存 -->
<!--共有三種策略,分別爲LRU(Least Recently Used 最近最少使用)、LFU(Less Frequently Used最不常用的)、FIFO(first in first out先進先出) -->
在SpringBoot中指定配置:
# 配置緩存,記住類型要選ehcache,否則ehcache配置文件中的配置將無效
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
接着便可以在服務類目使用緩存了。
簡單使用如下:
@Service
@Slf4j
public class UserServiceImpl implements UserService {
/**
* The User mapper.
*/
@Autowired
UserMapper userMapper;
private final String cacheName = "userCache";
private final String cacheKey = "'user'";
//* @Cacheable : Spring在每次執行前都會檢查Cache中是否存在相同key的緩存元素,如果存在就不再執行該方法,而是直接從緩存中獲取結果進行返回,否則纔會執行並將返回結果存入指定的緩存中。
//* @CacheEvict : 清除緩存。
//* @CachePut : @CachePut也可以聲明一個方法支持緩存功能。使用@CachePut標註的方法在執行前不會去檢查緩存中是否存在之前執行過的結果,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中。
@Override
@Cacheable(value = cacheName, key = cacheKey)
public List<User> selectAll() {
log.info("未讀取緩存");
return userMapper.findAll();
}
@Override
@CacheEvict(value = cacheName, key = cacheKey)
public Boolean insertUser(User user) {
return userMapper.insertSelective(user);
}
@Override
@Cacheable(value = cacheName, key = "'user_'+ #id")
public User selectById(long id) {
log.info("未讀取緩存");
return userMapper.selectByPrimaryKey(id);
}
@Override
@CacheEvict(value = cacheName, key = cacheKey)
public Boolean updateUser(User user) {
return userMapper.updateByPrimaryKey(user);
}
@Override
@CacheEvict(value = cacheName, key = cacheKey)
public Boolean deleteUser(long id) {
return userMapper.deleteByPrimaryKey(id);
}
}
Demo源碼已上傳至GitHub:https://github.com/liaozihong/SpringBoot-Learning/tree/master/SpringBoot-Mybatis-Ehcache