springboot-3-整合ehcache缓存

整合ehcache

一、maven引入

    <!-- 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>

二、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">
<cache
        name="student"
        eternal="false"
        maxElementsInMemory="100"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="0"
        timeToLiveSeconds="300"
        memoryStoreEvictionPolicy="LRU" />
</ehcache>
maxElementsInMemory:
内存缓存中最多能够存放的元素数量,若放入Cache中的元素超过这个数值,则有如下两种状况
overflowToDisk:
若overflowToDisk为true,则会将cache中多出的元素放入磁盘文件中,
若为false,则会:根据memoryStoreEvictionPolicy策略替换cache中原有的元素
eternal:
缓存中对象是否永久有效
timeToIdleSeconds:
缓存数据在失效前的容许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
timeToLiveSeconds:
缓存数据的总的存活时间(单位:秒),仅当eternal=false时使用,从建立开始计时,失效结束。
memoryStoreEvictionPolicy:
内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存  共有三种策略,分别为LRU(最近最少使用)、LFU(最经常使用的)、FIFO(先进先出)
**能够配置多个缓存

三、appliocation.properties配置

#ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
spring.cache.cache-names=student

这里 classpath:ehcache.xml 是第二步的ehcache配置文件的路径,放在类路径下。spring

student 是配置文件里命名的缓存名,可配置多个,用","逗号分隔缓存

四、开启缓存

在springboot启动类上,添加@EnableCaching注解,开启缓存springboot

五、spring注解用法

@Cacheableapp

@CacheEvictmaven

@CachePutspring-boot

@Cachingspa

@Cacheable(value=" ",key=" ")code

value 为缓存名,key为键名。该注解注解的方法,在执行时先进缓存查看缓存中是否有键值对应元素,有则直接返回缓存中数据,无则执行方法,返回方法执行结果,并存入缓存。xml

@CacheEvict(value=" ",key=" ")对象

该注解一般放在delete方法上,执行时直接清理缓存中key对应键值的的元素。

@CachePut

该注解不会影响方法的执行,每次方法执行后将执行结果存入缓存,以key值为键

@Caching

该注解注解的方法执行时会直接清空缓存。

相关文章
相关标签/搜索