SpringBoot整合Ehcache

本文详细介绍如何在SpringBoot项目中整合Ehcache缓存框架,包括配置步骤、注解使用及测试方法,并解析@Cacheable与@CacheEvict的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、SpringBoot整合Ehcache

1. Ehcache 简介

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
主要的特性有:

  1. 快速
  2. 简单
  3. 多种缓存策略
  4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题
  5. 缓存数据会在虚拟机重启的过程中写入磁盘
  6. 可以通过RMI、可插入API等方式进行分布式缓存
  7. 具有缓存和缓存管理器的侦听接口
  8. 支持多缓存管理器实例,以及一个实例的多个缓存区域
  9. 提供Hibernate的缓存实现
2. 引入相关依赖
<!-- Spring Boot缓存支持启动器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--Ehcache坐标-->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
3. 创建ehcache.xml配置文件 (配置文件模板在Ehcache jar包中找) 注意:在Ehcache标签中添加属性 maxBytesLocalHeap=“500M”
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"  maxBytesLocalHeap="500M">
    <!--磁盘缓存-->
    <diskStore path="java.io.tmpdir"/>

    <!--强制默认缓存配置。这些设置将应用于缓存使用CacheManager以编程方式创建。添加(字符串cacheName) -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- 自定义缓存策略 注意:定义多个自定义缓存策略,他们的name值不一样  在application.properties中配置该文件位置-->
    <cache name="webAudit">   <!-- name:自定义缓存策略名   方上使用@Cacheable(value = "webAudit") -->
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        maxElementsOnDisk="10000000"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>
4. 在application.yml配置文件中指定ehcache.xml位置
#ehcache配置
spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml    #ehcache.xml文件位置
5. 在启动类上添加@EnableCaching 注解开启缓存
6. 在需要缓存的方法上添加注解 @Cacheable(value = “webAudit”) value:配置文件中name的值
@Override
@Cacheable(value = "webAudit")
public MerchWebAudit findByid(Long id) {
    MerchWebAudit result = merchWebAuditRepository.getOne(id);
    return result;
}
7. 测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = JpademoApplication.class)
public class JpademoApplicationTests {
    @Autowired
    private MerchWebAuditServiceImpl merchWebAuditService;

    @Test
    public void findById() {
        System.out.println(merchWebAuditService.findByid(1L));
        System.out.println(merchWebAuditService.findByid(1L));
    }

}

未缓存前: 方法上未添加@Cacheable(value = “webAudit”),执行了两次sql语句
在这里插入图片描述
缓存后:执行了一次sql语句,第二次查询直接中缓存中查找
在这里插入图片描述

注意事项:实现缓存对象一定要实现序列化接口,否则会报NoSerializableException

二、注解详解 @Cacheable与@CacheEvict

1. @Cacheable

作用:把方法返回值添加到Ehcache中做缓存
value属性:指定一个Ehcache配置文件中的缓存策略,即name属性的值,如果没有给定value,name则表示使用默认的缓存机制。

<cache name="webAudit">   <!-- name:自定义缓存策略名   方上使用@Cacheable(value = "webAudit") -->
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="120"
    timeToLiveSeconds="120"
    maxElementsOnDisk="10000000"
    diskExpiryThreadIntervalSeconds="120"
    memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
</cache>

key属性:给存储的值起个名称,即key(默认为key="#参数名")。 在查询时如果有名称相同的key,那么直接从缓存中将数据返回。

@Override
@Cacheable(value = "webAudit",key = "#id") //此注解将当前方法的结果缓存到Ehcache中,key为当前缓存值的键
                                            //key的默认值为当前方法参数,显示定义为 key="#参数名" ,是否到缓存中查找取决于是否存在相同的key,即方法中传递进来的参数(即key)是否存在
public MerchWebAudit findByid(Long id) {
    MerchWebAudit result = merchWebAuditRepository.getOne(id);
    if(result == null){
        throw new MobaoException("页面初始化失败!",2);
    }
    return result;
}
2. @CacheEvict

作用:清空缓存,以达到缓存同步效果。

注意:在对数据看库进行更新方法上使用,是缓存失效,重新从数据中进行查询并将新的结果缓存到Ehcache中,达到缓存同步效果

value属性:清除指定缓存策略缓存的对象
allEntries属性: 默认false

使用方式
在对数据进行更新,缓存需要发生改变的方法上添加如下注解
@CacheEvict(value="webAudit",allEntries=true)

如:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值