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