一文玩转 EhCache 缓存框架!
Ehcache 介紹
EhCache 從 Hibernate 發(fā)展而來(lái),是一個(gè)純Java的進(jìn)程內(nèi)緩存框架,具有快速、精干等特點(diǎn)。Ehcache是一種廣泛使用的開(kāi)源Java分布式緩存。主要面向通用緩存,Java EE和輕量級(jí)容器。它具有內(nèi)存和磁盤(pán)存儲(chǔ),緩存加載器,緩存擴(kuò)展,緩存異常處理程序,一個(gè)gzip緩存servlet過(guò)濾器,支持REST和SOAP api等特點(diǎn)。
主要特性:
快速,簡(jiǎn)單
多種緩存策略
緩存數(shù)據(jù)有兩級(jí):內(nèi)存和磁盤(pán),因此無(wú)需擔(dān)心容量問(wèn)題
緩存數(shù)據(jù)會(huì)在虛擬機(jī)重啟的過(guò)程中寫(xiě)入磁盤(pán)
可以通過(guò)RMI、可插入API等方式進(jìn)行分布式緩存
具有緩存和緩存管理器的偵聽(tīng)接口
支持多緩存管理器實(shí)例,以及一個(gè)實(shí)例的多個(gè)緩存區(qū)域
提供Hibernate的緩存實(shí)現(xiàn)
Show me the code
在 pom.xml 文件中添加 Ehcache 依賴(lài)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId> </dependency>不需要配置version,SpringBoot的根pom已經(jīng)對(duì)版本號(hào)做了統(tǒng)一聲明!
配置文件:
在配置文件 application.yaml 中配置 ehcache 的相關(guān)參數(shù),具體內(nèi)容如下:
spring:application:name:?spring-boot-bulking-ehcachecache:type:?ehcacheehcache:config:?classpath:/ehcache.xmlspring.cache.type 聲明spring框架使用哪一種類(lèi)型的緩存,因?yàn)閟pring框架提供了多種緩存可供選擇。
添加 Ehcache 配置:
在src/main/resources 目錄下,創(chuàng)建配置文件ehcache.xml ,內(nèi)容如下:
<ehcache?name="test"><diskStore?path="java.io.tmpdir"/><defaultCachemaxEntriesLocalHeap="1000"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="600"overflowToDisk="true"memoryStoreEvictionPolicy="LRU"></defaultCache><cache?name="userCache"maxEntriesLocalHeap="200"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="600"overflowToDisk="true"></cache> </ehcache>參數(shù)含義:
diskStore:磁盤(pán)緩存位置
name:緩存名稱(chēng)
maxElementsInMemory:內(nèi)存中最大緩存對(duì)象數(shù)
maxElementsOnDisk:硬盤(pán)中最大緩存對(duì)象數(shù),若是0表示無(wú)窮大
eternal:true表示對(duì)象永不過(guò)期,此時(shí)會(huì)忽略timeToIdleSeconds和timeToLiveSeconds屬性,默認(rèn)為false
timeToIdleSeconds:設(shè)定允許對(duì)象處于空閑狀態(tài)的最長(zhǎng)時(shí)間,以秒為單位。當(dāng)對(duì)象自從最近一次被訪(fǎng)問(wèn)后,如果處于空閑狀態(tài)的時(shí)間超過(guò)了timeToIdleSeconds屬性值,這個(gè)對(duì)象就會(huì)過(guò)期,EHCache將把它從緩存中清空。只有當(dāng)eternal屬性為false,該屬性才有效。如果該屬性值為0,則表示對(duì)象可以無(wú)限期地處于空閑狀態(tài)
timeToLiveSeconds:設(shè)定對(duì)象允許存在于緩存中的最長(zhǎng)時(shí)間,以秒為單位。當(dāng)對(duì)象自從被存放到緩存中后,如果處于緩存中的時(shí)間超過(guò)了 timeToLiveSeconds屬性值,這個(gè)對(duì)象就會(huì)過(guò)期,EHCache將把它從緩存中清除。只有當(dāng)eternal屬性為false,該屬性才有效。如果該屬性值為0,則表示對(duì)象可以無(wú)限期地存在于緩存中。timeToLiveSeconds必須大于timeToIdleSeconds屬性,才有意義
overflowToDisk:當(dāng)內(nèi)存中對(duì)象數(shù)量達(dá)到maxElementsInMemory時(shí),Ehcache將會(huì)對(duì)象寫(xiě)到磁盤(pán)中。
diskSpoolBufferSizeMB:磁盤(pán)緩存區(qū)大小,默認(rèn)為30MB。每個(gè)Cache都應(yīng)該有自己的一個(gè)緩存區(qū)。
diskPersistent:是否緩存虛擬機(jī)重啟期數(shù)據(jù)。
diskExpiryThreadIntervalSeconds:磁盤(pán)失效線(xiàn)程運(yùn)行時(shí)間間隔,默認(rèn)是120秒。
memoryStoreEvictionPolicy:當(dāng)達(dá)到maxElementsInMemory限制時(shí),Ehcache將會(huì)根據(jù)指定的策略去清理內(nèi)存。默認(rèn)策略是LRU(最近最少使用)。你可以設(shè)置為FIFO(先進(jìn)先出)或是LFU(較少使用)。
clearOnFlush:內(nèi)存數(shù)量最大時(shí)是否清除。
開(kāi)啟緩存:
入口啟動(dòng)類(lèi)添加注解 @EnableCaching
@SpringBootApplication(exclude?=?{DataSourceAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class}) @EnableCaching??//?開(kāi)啟緩存,Spring?Boot?會(huì)自動(dòng)配置緩存的?CacheManager public?class?StartApplication?{public?static?void?main(String[]?args)?{SpringApplication.run(StartApplication.class,?args);} }緩存業(yè)務(wù)使用:
@Component @CacheConfig(cacheNames?=?"userCache") public?class?UserService?{@Cacheable(key?=?"#id")public?User?getUserById(Long?id)?{System.out.println("緩存中無(wú)值");User?user?=?User.builder().id(id).userName("雪糕("?+?id?+?")").age(18).address("杭州").build();return?user;}@CachePut(key?=?"#user.id")public?User?updateUser(User?user)?{user.setUserName("雪糕(new?name)");return?user;}@CacheEvict(key?=?"#id")public?void?deleteById(Long?id)?{System.out.println("db?刪除數(shù)據(jù),id="?+?id);} }@CacheConfig ?作用于類(lèi)上,用來(lái)描述該類(lèi)中所有方法使用的緩存名稱(chēng)。當(dāng)然也可以不使用該注解,直接在具體方法上的緩存注解里配置名稱(chēng)
@Cacheable 用于查詢(xún)方法上,表示將一個(gè)方法的返回值緩存起來(lái)。默認(rèn)情況下,緩存的 key 就是方法的參數(shù),緩存的 value 就是方法的返回值
@CachePut ?更新操作,當(dāng)數(shù)據(jù)庫(kù)中的數(shù)據(jù)更新后,緩存中的數(shù)據(jù)也要跟著更新,使用該注解,可以將方法的返回值自動(dòng)更新到已經(jīng)存在的 key 上
@CacheEvict ?刪除操作,當(dāng)數(shù)據(jù)庫(kù)中的數(shù)據(jù)刪除后,相關(guān)的緩存數(shù)據(jù)也要自動(dòng)清除。
除了采用 @Cacheable 、@CachePut 等方法注解解耦式操作緩存外,我們也可以使用 CacheManager顯示方式手動(dòng)來(lái)操作緩存。
CacheManager
Spring定義了CacheManager和Cache接口統(tǒng)一不同的緩存技術(shù)。其中CacheManager是Spring提供的各種緩存技術(shù)的抽象接口,而Cache接口包含緩存的讀、寫(xiě)、刪等各種操作。
針對(duì)不同的緩存技術(shù),需要實(shí)現(xiàn)不同的CacheManager,Spring預(yù)先定義了主流緩存框架的cacheManger實(shí)現(xiàn)類(lèi)
| SimpleCacheManager | 使用簡(jiǎn)單的Collection來(lái)存儲(chǔ)緩存,主要用于測(cè)試 |
| ConcurrentMapCacheManager | 使用ConcurrentMap作為緩存技術(shù)(默認(rèn)) |
| NoOpCacheManager | 測(cè)試用 |
| EhCacheCacheManager | 使用EhCache作為緩存技術(shù),以前在hibernate的時(shí)候經(jīng)常用 |
| GuavaCacheManager | 使用google guava的GuavaCache作為緩存技術(shù) |
| HazelcastCacheManager | 使用Hazelcast作為緩存技術(shù) |
| JCacheCacheManager | 使用JCache標(biāo)準(zhǔn)的實(shí)現(xiàn)作為緩存技術(shù),如Apache Commons JCS |
| RedisCacheManager | 使用Redis作為緩存技術(shù) |
| CaffeineCacheManager | 使用Caffeine作為緩存技術(shù) |
Spring Boot 為我們預(yù)留接口擴(kuò)展,方便我們自動(dòng)配置 EhCache、Redis、Guava、ConcurrentMap等緩存,默認(rèn)使用ConcurrentMapCacheManager。Spring Boot的application.yaml配置文件,使用spring.cache前綴屬性進(jìn)行配置。
本文我們使用 EhCache 緩存,代碼示例如下:
@Component public?class?UserCacheManager?{@Resourceprivate?CacheManager?cacheManager;public?User?getUserById(Long?id)?{Cache?cache?=?cacheManager.getCache("userCache");User?user?=?cache.get(id,?User.class);if?(user?==?null)?{System.out.println("緩存中無(wú)值");user?=?User.builder().id(id).userName("雪糕("?+?id?+?")").age(18).address("杭州").build();cache.put(id,?user);}return?user;}public?User?updateUser(User?user)?{user.setUserName("雪糕(new?name)");Cache?cache?=?cacheManager.getCache("userCache");cache.put(user.getId(),?user);return?user;}public?void?deleteById(Long?id)?{Cache?cache?=?cacheManager.getCache("userCache");cache.evict(id);System.out.println("db?刪除數(shù)據(jù),id="?+?id);} }演示代碼地址
https://github.com/aalansehaiyang/spring-boot-bulking??模塊:spring-boot-bulking-ehcache 往期推薦Spring為什么建議構(gòu)造器注入?
超級(jí)詳細(xì)的Spring Boot 注解總結(jié)
Spring中的重試功能!嗯,有點(diǎn)東西
總結(jié)
以上是生活随笔為你收集整理的一文玩转 EhCache 缓存框架!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 优雅统计代码耗时的4种方法!
- 下一篇: 工作总结:日志打印的15个建议