摘要
本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程。
概念
Ehcache是一种Java缓存框架,支持多种缓存策略,如:
- 最近最少使用LRU:当缓存达到最大容量时,会将最近最少使用的元素淘汰。
- 最少最近使用LFU:根据元素被访问的频率来淘汰元素,最少被访问的元素会被优先淘汰。
- 先进先出FIFO:按元素进入缓存的时间顺序淘汰元素,先进入的元素会被优先淘汰。
内存与磁盘持久化存储:
Ehcache支持将数据存储在内存中,以实现快速访问。当内存不足时,Ehcache可以将数据交换到磁盘,确保缓存数据不会因为内存限制而丢失。磁盘存储路径可以通过配置灵活指定,即使在系统重启后也能恢复缓存数据。提供多种持久化策略,包括本地临时交换localTempSwap和自定义持久化实现。
配置灵活性:
可通过配置ehcache.xml文件,放在启动类资源目录里,可自定义缓存策略,LRU,diskExpiryThreadIntervalSeconds。
编码示例
引入依赖:
pom.xml指定ehcache坐标并排除slf4j
xml
<!-- Ehcache 坐标 -->
<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文件:
xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir/ehcache"/> <!-- 定义磁盘存储路径,将缓存数据存储在临时目录下 -->
<!--
参数说明:
maxElementsInMemory 内存中最多存储的元素数量
eternal 是否为永生缓存,false表示元素有生存和闲置时间
timeToIdleSeconds 元素闲置 120 秒后失效
timeToLiveSeconds 元素存活 120 秒后失效
maxElementsOnDisk 磁盘上最多存储的元素数量
diskExpiryThreadIntervalSeconds 磁盘清理线程运行间隔
memoryStoreEvictionPolic 内存存储的淘汰策略,采用 LRU(最近最少使用)
-->
<!-- defaultCache:echcache 的默认缓存策略-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- 自定义缓存策略 这里的name是用于缓存名指定时 需要对应缓存名添加-->
<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的缓存文件路径
yaml
spring:
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
自定义缓存get/set方式:
利用CacheManager处理缓存:
typescript
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;
/**
* 根据名称获取缓存数据
* @param cacheName cache名称
* @param keyName cache中对应key名称
* @return cache数据
*/
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<>();
}
/**
* 往缓存中存放数据 名字区分
* @param cacheName cache名称
* @param keyName cache中对应key名称
* @param dataList 存放数据
*/
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开启程序缓存
java
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!");
}
}
编辑测试类:
kotlin
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("获取缓存数据:" + cacheData.toString());
}
}
测试结果:

总结
以上我们了解了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程。
关注公众号:咖啡Beans
在这里,我们专注于软件技术的交流与成长,分享开发心得与笔记,涵盖编程、AI、资讯、面试等多个领域。无论是前沿科技的探索,还是实用技巧的总结,我们都致力于为大家呈现有价值的内容。期待与你共同进步,开启技术之旅。