詳解SpringBoot+Ehcache使用示例
摘要
本文介紹了SpringBoot中配置Ehcache、自定義get/set方式,并實際使用緩存的過程。
概念
Ehcache是一種Java緩存框架,支持多種緩存策略,如:
- 最近最少使用LRU:當(dāng)緩存達(dá)到最大容量時,會將最近最少使用的元素淘汰。
- 最少最近使用LFU:根據(jù)元素被訪問的頻率來淘汰元素,最少被訪問的元素會被優(yōu)先淘汰。
- 先進(jìn)先出FIFO:按元素進(jìn)入緩存的時間順序淘汰元素,先進(jìn)入的元素會被優(yōu)先淘汰。
內(nèi)存與磁盤持久化存儲:
Ehcache支持將數(shù)據(jù)存儲在內(nèi)存中,以實現(xiàn)快速訪問。當(dāng)內(nèi)存不足時,Ehcache可以將數(shù)據(jù)交換到磁盤,確保緩存數(shù)據(jù)不會因為內(nèi)存限制而丟失。磁盤存儲路徑可以通過配置靈活指定,即使在系統(tǒng)重啟后也能恢復(fù)緩存數(shù)據(jù)。提供多種持久化策略,包括本地臨時交換localTempSwap和自定義持久化實現(xiàn)。
配置靈活性:
可通過配置ehcache.xml文件,放在啟動類資源目錄里,可自定義緩存策略,LRU,diskExpiryThreadIntervalSeconds。
編碼示例
引入依賴:
pom.xml指定ehcache坐標(biāo)并排除slf4j
<!-- Ehcache 坐標(biāo) -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.9.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
配置ehcache.xml文件:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir/ehcache"/> <!-- 定義磁盤存儲路徑,將緩存數(shù)據(jù)存儲在臨時目錄下 -->
<!--
參數(shù)說明:
maxElementsInMemory 內(nèi)存中最多存儲的元素數(shù)量
eternal 是否為永生緩存,false表示元素有生存和閑置時間
timeToIdleSeconds 元素閑置 120 秒后失效
timeToLiveSeconds 元素存活 120 秒后失效
maxElementsOnDisk 磁盤上最多存儲的元素數(shù)量
diskExpiryThreadIntervalSeconds 磁盤清理線程運行間隔
memoryStoreEvictionPolic 內(nèi)存存儲的淘汰策略,采用 LRU(最近最少使用)
-->
<!-- defaultCache:echcache 的默認(rèn)緩存策略-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- 自定義緩存策略 這里的name是用于緩存名指定時 需要對應(yīng)緩存名添加-->
<cache name="cacheName"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
配置文件:
application.yml指定spring的緩存文件路徑
spring:
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
自定義緩存get/set方式:
利用CacheManager處理緩存:
package org.coffeebeans.ehcache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* <li>ClassName: EhCacheService </li>
* <li>Author: OakWang </li>
*/
@Service
public class EhCacheService {
@Autowired
private CacheManager cacheManager;
/**
* 根據(jù)名稱獲取緩存數(shù)據(jù)
* @param cacheName cache名稱
* @param keyName cache中對應(yīng)key名稱
* @return cache數(shù)據(jù)
*/
public List<?> getCacheData(String cacheName, String keyName){
Cache cache = cacheManager.getCache(cacheName);
if (!Objects.isNull(cache)) {
Element element = cache.get(keyName);
if (!Objects.isNull(element)) {
return (List<?>) element.getObjectValue();
}
}
return new ArrayList<>();
}
/**
* 往緩存中存放數(shù)據(jù) 名字區(qū)分
* @param cacheName cache名稱
* @param keyName cache中對應(yīng)key名稱
* @param dataList 存放數(shù)據(jù)
*/
public void putCacheData(String cacheName, String keyName, List<?> dataList){
Cache cache = cacheManager.getCache(cacheName);
if (Objects.isNull(cache)){
cache = new Cache(cacheName,1000,true,false,0,0);
}
Element newElement = new Element(keyName, dataList);
cache.put(newElement);
}
}
啟動類加注解:
@EnableCaching開啟程序緩存
package org.coffeebeans;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
/**
* <li>ClassName: EhCacheApplication </li>
* <li>Author: OakWang </li>
*/
@Slf4j
@SpringBootApplication
@EnableCaching//開啟程序緩存
public class EhCacheApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(EhCacheApplication.class);
springApplication.run(args);
log.info("EhCacheApplication start success!");
}
}
編輯測試類:
package org.coffeebeans.ehcache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
/**
* <li>ClassName: TestEhCache </li>
* <li>Author: OakWang </li>
*/
@Service
public class TestEhCache {
@Autowired
private EhCacheService ehCacheService;
public void testEhCache() {
ehCacheService.putCacheData("cacheName", "keyName", Collections.singletonList("value"));
List<?> cacheData = ehCacheService.getCacheData("cacheName", "keyName");
System.out.println("獲取緩存數(shù)據(jù):" + cacheData.toString());
}
}
測試結(jié)果:

總結(jié)
以上我們了解了SpringBoot中配置Ehcache、自定義get/set方式,并實際使用緩存的過程。
到此這篇關(guān)于詳解SpringBoot+Ehcache使用示例的文章就介紹到這了,更多相關(guān)SpringBoot+Ehcache使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA快速搭建Java開發(fā)環(huán)境的教程圖解
這篇文章主要介紹了IDEA如何快速搭建Java開發(fā)環(huán)境,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11
Springboot3集成Knife4j的步驟以及使用(最完整版)
這篇文章主要介紹了Springboot3集成Knife4j的步驟以及使用的相關(guān)資料,Knife4j是一種增強Swagger的工具,支持黑色主題和更多配置選項,它與swagger-bootstrap-ui相比,提供了更現(xiàn)代的外觀和更多的功能,需要的朋友可以參考下2024-11-11
java中如何使用BufferedImage判斷圖像通道順序并轉(zhuǎn)RGB/BGR
這篇文章主要介紹了java中如何BufferedImage判斷圖像通道順序并轉(zhuǎn)RGB/BGR的相關(guān)資料,需要的朋友可以參考下2017-03-03
spring基于通用Dao的多數(shù)據(jù)源配置詳解
這篇文章主要為大家詳細(xì)介紹了spring基于通用Dao的多數(shù)據(jù)源配置,具有一定的參考價值,感興趣的小伙伴們可以參考一下解2018-03-03

