springboot-3-整合ehcache緩存


整合ehcache

1、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>

2、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(先進先出)
**可以配置多個緩存

3、appliocation.properties配置

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

這里 classpath:ehcache.xml 是第二步的ehcache配置文件的路徑,放在類路徑下。

student 是配置文件里命名的緩存名,可配置多個,用","逗號分隔

4、開啟緩存

在springboot啟動類上,添加@EnableCaching注解,開啟緩存

5、spring注解用法

@Cacheable

@CacheEvict

@CachePut

@Caching

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

value 為緩存名,key為鍵名。該注解注解的方法,在執行時先進緩存查看緩存中是否有鍵值對應元素,有則直接返回緩存中數據,無則執行方法,返回方法執行結果,並存入緩存。

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

該注解通常放在delete方法上,執行時直接清理緩存中key對應鍵值的的元素。

@CachePut

該注解不會影響方法的執行,每次方法執行后將執行結果存入緩存,以key值為鍵

@Caching

該注解注解的方法執行時會直接清空緩存。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM