SpringBoot整合EhCache

本文介绍了如何在Spring Boot应用中启用和配置Ehcache缓存,包括添加依赖、配置参数、创建ehcache.xml文件以及在代码中使用@Cacheable、@CachePut和@CacheEvict注解进行缓存操作。示例代码已上传至Git仓库,供读者直接运行和学习。
摘要由CSDN通过智能技术生成

1.开启

@EnableCaching

2.添加依赖

        <!--开启 cache 缓存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.8.1</version>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>net.sf.ehcache</groupId>-->
<!--            <artifactId>ehcache</artifactId>-->
<!--            <version>2.10.6</version>-->
<!--        </dependency>-->

  3.添加配置参数application.properties

spring.cache.ehcache.config= classpath:ehcache.xml

也可以直接在Application.java上使用注解

@ImportResource(locations = {"classpath:ehcache.xml"})

  4.添加ehcache.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://www.ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--timeToIdleSeconds 当缓存闲置n秒后销毁 -->
    <!--timeToLiveSeconds 当缓存存活n秒后销毁 -->
    <!-- 缓存配置
        name:缓存名称。
        maxElementsInMemory:缓存最大个数。
        eternal:对象是否永久有效,一但设置了,timeout将不起作用。
        timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
        timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
        overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
        maxElementsOnDisk:硬盘最大缓存个数。
        diskPersistent:是否缓存虚拟机重启期数据 Whether the disk
        store persists between restarts of the Virtual Machine. The default value
        is false.
        diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。  memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是
LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
        clearOnFlush:内存数量最大时是否清除。 -->
    <!-- 磁盘缓存位置 -->
    <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="books"
           eternal="false"
           timeToIdleSeconds="2400"
           timeToLiveSeconds="2400"
           maxEntriesLocalHeap="10000"
           maxEntriesLocalDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LRU">
    </cache>

</ehcache>

  

  5.代码修改

在需要的方法上添加类似这样的注解.

查询方法:@Cacheable

保存或者更新方法:@CachePut

删除方法:@CacheEvict

@Cacheable(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
@CachePut(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#book.id)")
@CacheEvict(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
    @Override
    @Cacheable(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
    public Book findBook(String bookId) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("执行方法,不使用缓存:{}",bookId);
        return new Book("1","Query","1");
    }

    @Override
    @CachePut(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#book.id)")
    public Book savaBook(Book book) {
        return book;
    }

    @Override
    @CacheEvict(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
    public String deleteBook(String bookId) {
        return bookId;
    }

 

为了减少些代码,

比如

@Cacheable(cacheNames="books",

也可以在类上使用@CacheConfig注解,整个类都是这个缓存设置了.

@CacheConfig(cacheNames = "books")

 

 代码已经上传,可以直接运行

https://gitee.com/johnnycode/cdlig-demo.git

xsd下载路径:

https://www.ehcache.org/ehcache.xsd

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞翔的咩咩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值