SpringBoot手動使用EhCache的方法示例
SpringBoot在annotation的層面實現(xiàn)了數(shù)據(jù)緩存的功能,基于Spring的AOP技術。所有的緩存配置只是在annotation層面配置,像聲明式事務一樣。
Spring定義了CacheManager和Cache接口統(tǒng)一不同的緩存技術。其中CacheManager是Spring提供的各種緩存技術的抽象接口。而Cache接口包含緩存的各種操作。
CacheManger
針對不同的緩存技術,需要實現(xiàn)不同的cacheManager,Spring定義了如下的cacheManger實現(xiàn)。
| CacheManger | 描述 |
|---|---|
| SimpleCacheManager | 使用簡單的Collection來存儲緩存,主要用于測試 |
| ConcurrentMapCacheManager | 使用ConcurrentMap作為緩存技術(默認) |
| NoOpCacheManager | 測試用 |
| EhCacheCacheManager | 使用EhCache作為緩存技術,以前在hibernate的時候經(jīng)常用 |
| GuavaCacheManager | 使用google guava的GuavaCache作為緩存技術 |
| HazelcastCacheManager | 使用Hazelcast作為緩存技術 |
| JCacheCacheManager | 使用JCache標準的實現(xiàn)作為緩存技術,如Apache Commons JCS |
| RedisCacheManager | 使用Redis作為緩存技術 |
常規(guī)的SpringBoot已經(jīng)為我們自動配置了EhCache、Collection、Guava、ConcurrentMap等緩存,默認使用ConcurrentMapCacheManager。SpringBoot的application.properties配置文件,使用spring.cache前綴的屬性進行配置。
application配置
spring.cache.type=#緩存的技術類型 spring.cache.cache-names=應用程序啟動創(chuàng)建緩存的名稱 spring.cache.ehcache.config=ehcache的配置文件位置 spring.cache.infinispan.config=infinispan的配置文件位置 spring.cache.jcache.config=jcache配置文件位置 spring.cache.jcache.provider=當多個jcache實現(xiàn)類時,指定選擇jcache的實現(xiàn)類
入口類配置
加入注解 @EnableCaching
緩存注解
| 注解 | 描述 |
|---|---|
| @Cacheable | 在調(diào)用方法之前,首先應該在緩存中查找方法的返回值,如果這個值能夠找到,就會返回緩存的值。否則,這個方法就會被調(diào)用,返回值會放到緩存之中。 |
| @CachePut | 將方法的返回值放到緩存中。在方法的調(diào)用前并不會檢查緩存,方法始終都會被調(diào)用。 |
| @CacheEvict | 在緩存中清除一個或多個條目。 |
| @Caching | 分組的注解,能夠同時應用多個其他的緩存注解。 |
手動使用EhCache
在實際開發(fā)過程中,存在不使用注解,需要自己添加緩存的情況。下面就以Ehcache為例,簡單寫一下配置過程。
1. 添加依賴
引入springboot-cache和ehcache。需要注意,EhCache不需要配置version,SpringBoot的根pom已經(jīng)集成了。
<!-- 緩存 --> <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. 入口類配置
加入注解 @EnableCaching
@SpringBootApplication
@EnableCaching
public class DemoApplication {
}
3. EhCache配置
在src\main\resources目錄下,添加ehcache.xml文件,內(nèi)容見文末。
4. application.application配置
# 配置ehcache緩存 spring.cache.type=ehcache # 指定ehcache配置文件路徑 spring.cache.ehcache.config=classpath:/ehcache.xml
5. 使用Cache
注入SpringBoot自動配置的bean,org.springframework.cache.CacheManager。
一個簡單的測試類:
package com.bbf.frame.test;
import com.bbf.frame.Application;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class TestCache {
@Resource
private CacheManager cacheManager;
@Test
public void cacheTest() {
// 顯示所有的Cache空間
System.out.println(StringUtils.join(cacheManager.getCacheNames(), ","));
Cache cache = cacheManager.getCache("userCache");
cache.put("key", "123");
System.out.println("緩存成功");
String res = cache.get("key", String.class);
System.out.println(res);
}
}
附錄 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">
<!-- 指定一個文件目錄,當EHCache把數(shù)據(jù)寫到硬盤上時,將把數(shù)據(jù)寫到這個文件目錄下 -->
<diskStore path = "java.io.tmpdir"/>
<!-- 默認的管理策略 -->
<defaultCache
eternal = "false"
maxElementsInMemory = "10000"
overflowToDisk = "true"
diskPersistent = "false"
timeToIdleSeconds = "120"
timeToLiveSeconds = "120"
diskExpiryThreadIntervalSeconds = "120"
memoryStoreEvictionPolicy = "LRU"/>
<!-- 此緩存最多可以存活timeToLiveSeconds秒,如果期間超過timeToIdleSeconds秒未訪問,緩存失效 -->
<cache
name = "userCache"
eternal = "false"
maxElementsInMemory = "100"
overflowToDisk = "false"
diskPersistent = "false"
timeToIdleSeconds = "120"
timeToLiveSeconds = "180"
memoryStoreEvictionPolicy = "LRU"/>
<!-- maxElementsInMemory 內(nèi)存中最大緩存對象數(shù),看著自己的heap大小來搞 -->
<!-- eternal:true表示對象永不過期,此時會忽略timeToIdleSeconds和timeToLiveSeconds屬性,默認為false -->
<!-- maxElementsOnDisk:硬盤中最大緩存對象數(shù),若是0表示無窮大 -->
<!-- overflowToDisk:true表示當內(nèi)存緩存的對象數(shù)目達到了maxElementsInMemory界限后,
會把溢出的對象寫到硬盤緩存中。注意:如果緩存的對象要寫入到硬盤中的話,則該對象必須實現(xiàn)了Serializable接口才行。-->
<!-- diskSpoolBufferSizeMB:磁盤緩存區(qū)大小,默認為30MB。每個Cache都應該有自己的一個緩存區(qū)。-->
<!-- diskPersistent:是否緩存虛擬機重啟期數(shù)據(jù) -->
<!-- diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認為120秒 -->
<!-- timeToIdleSeconds: 設定允許對象處于空閑狀態(tài)的最長時間,以秒為單位。當對象自從最近一次被訪問后,
如果處于空閑狀態(tài)的時間超過了timeToIdleSeconds屬性值,這個對象就會過期,
EHCache將把它從緩存中清空。只有當eternal屬性為false,該屬性才有效。如果該屬性值為0,
則表示對象可以無限期地處于空閑狀態(tài) -->
<!-- timeToLiveSeconds:設定對象允許存在于緩存中的最長時間,以秒為單位。當對象自從被存放到緩存中后,
如果處于緩存中的時間超過了 timeToLiveSeconds屬性值,這個對象就會過期,
EHCache將把它從緩存中清除。只有當eternal屬性為false,該屬性才有效。如果該屬性值為0,
則表示對象可以無限期地存在于緩存中。timeToLiveSeconds必須大于timeToIdleSeconds屬性,才有意義 -->
<!-- memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,
Ehcache將會根據(jù)指定的策略去清理內(nèi)存??蛇x策略有:LRU(最近最少使用,默認策略)、
FIFO(先進先出)、LFU(最少訪問次數(shù))。-->
</ehcache>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot中實現(xiàn)異步調(diào)用@Async詳解
這篇文章主要介紹了SpringBoot中實現(xiàn)異步調(diào)用@Async詳解,在SpringBoot的日常開發(fā)中,一般都是同步調(diào)用的,但實際中有很多場景非常適合使用異步來處理,需要的朋友可以參考下2024-01-01
java web在高并發(fā)和分布式下實現(xiàn)訂單號生成唯一的解決方案
這篇文章主要介紹了java web在高并發(fā)和分布式下實現(xiàn)訂單號生成唯一的解決方案,需要的朋友可以參考下2017-11-11
java CompletableFuture實現(xiàn)異步編排詳解
這篇文章主要為大家介紹了java CompletableFuture實現(xiàn)異步編排詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01
SpringMVC處理器映射器HandlerMapping詳解
這篇文章主要介紹了SpringMVC處理器映射器HandlerMapping詳解,在SpringMVC中會有很多請求,每個請求都需要一個HandlerAdapter處理,具體接收到一個請求之后使用哪個HandlerAdapter進行處理呢,他們的過程是什么,需要的朋友可以參考下2023-09-09
Java開發(fā)環(huán)境配置及Vscode搭建過程
今天通過圖文并茂的形式給大家介紹Java開發(fā)環(huán)境配置及Vscode搭建過程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-07-07
淺談java面向?qū)ο?類,封裝,this,構(gòu)造方法)
下面小編就為大家?guī)硪黄獪\談java面向?qū)ο?類,封裝,this,構(gòu)造方法)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06

