<!-- 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>
<?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(先進先出)
**能夠配置多個緩存
#ehcache spring.cache.ehcache.config=classpath:ehcache.xml spring.cache.cache-names=student
這裏 classpath:ehcache.xml 是第二步的ehcache配置文件的路徑,放在類路徑下。spring
student 是配置文件裏命名的緩存名,可配置多個,用","逗號分隔緩存
在springboot啓動類上,添加@EnableCaching註解,開啓緩存springboot
@Cacheableapp
@CacheEvictmaven
@CachePutspring-boot
@Cachingspa
@Cacheable(value=" ",key=" ")code
value 爲緩存名,key爲鍵名。該註解註解的方法,在執行時先進緩存查看緩存中是否有鍵值對應元素,有則直接返回緩存中數據,無則執行方法,返回方法執行結果,並存入緩存。xml
@CacheEvict(value=" ",key=" ")對象
該註解一般放在delete方法上,執行時直接清理緩存中key對應鍵值的的元素。
@CachePut
該註解不會影響方法的執行,每次方法執行後將執行結果存入緩存,以key值爲鍵
@Caching
該註解註解的方法執行時會直接清空緩存。