Java實(shí)現(xiàn)本地緩存的四種方案(Guava Cache、Caffeine、Ehcach 和Spring Cache)
一、引言
在現(xiàn)代應(yīng)用程序開發(fā)中,緩存是提高性能和響應(yīng)速度的關(guān)鍵技術(shù)之一。Java 提供了多種本地緩存解決方案,每種方案都有其特點(diǎn)和適用場(chǎng)景。本文將介紹四種常見的 Java 本地緩存實(shí)現(xiàn):Guava Cache、Caffeine、Ehcache 和 Spring Cache。
二、Guava Cache
理論介紹
Guava Cache 是 Google Guava 庫的一部分,提供了輕量級(jí)的本地緩存功能。它具有以下特點(diǎn):
簡(jiǎn)單易用:API 設(shè)計(jì)簡(jiǎn)潔,易于集成到項(xiàng)目中。
自動(dòng)回收:支持基于時(shí)間或引用的自動(dòng)回收機(jī)制。
并發(fā)支持:內(nèi)置高效的并發(fā)控制,適合多線程環(huán)境。
實(shí)戰(zhàn)演示
pom
<dependencies>
<!-- Guava Cache -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1-jre</version>
</dependency>
</dependencies>
示例代碼
/**
* LocalCacheTest
* @author senfel
* @version 1.0
* @date 2024/12/20 17:17
*/
@SpringBootTest
public class LocalCacheTest {
/**
* guavaCache
* @author senfel
* @date 2024/12/20 17:19
* @return void
*/
@Test
public void guavaCache() throws Exception{
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) {
return "Value for " + key;
}
});
System.out.println(cache.get("key1")); // 輸出: Value for key1
}
三、Caffeine
理論介紹
Caffeine 是一個(gè)高性能的本地緩存庫,繼承了 Guava Cache 的優(yōu)點(diǎn)并進(jìn)行了優(yōu)化。它的特點(diǎn)包括:
高性能:比 Guava Cache 更快,特別是在高并發(fā)環(huán)境下。
靈活配置:支持多種緩存策略,如 LRU(最近最少使用)、LFU(最不經(jīng)常使用)等。
內(nèi)存友好:通過弱引用和軟引用來減少內(nèi)存占用。
實(shí)戰(zhàn)演示
pom
<dependencies>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.3</version>
</dependency>
</dependencies>
示例代碼
/**
* caffeineCache
* @author senfel
* @date 2024/12/20 17:25
* @return void
*/
@Test
public void caffeineCache() throws Exception{
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
cache.put("key1", "value1");
System.out.println(cache.getIfPresent("key1")); // 輸出: value1
}
四、Ehcache
理論介紹
Ehcache 是一個(gè)廣泛使用的開源緩存框架,適用于分布式和非分布式環(huán)境。它的特點(diǎn)有:
豐富的特性:支持多種緩存策略、持久化、集群等功能。
配置靈活:可以通過 XML 或注解進(jìn)行配置。
社區(qū)活躍:擁有龐大的用戶群體和活躍的社區(qū)支持。
實(shí)戰(zhàn)演示
pom
<dependencies>
<!-- Ehcache 核心庫 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
<!-- Ehcache 的 web 集群分布式緩存的支持 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-web</artifactId>
<version>2.0.4</version>
</dependency>
</dependencies>
ehcache.xml
<!-- ehcache.xml -->
<ehcache>
<cache name="exampleCache"
maxEntriesLocalHeap="100"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"/>
</ehcache>
示例代碼
/**
* ehcacheCache
* @author senfel
* @date 2024/12/20 17:31
* @return void
*/
@Test
public void ehcacheCache() throws Exception{
CacheManager cacheManager = CacheManager.create("D:\\workspace\\cce-demo\\src\\main\\resources\\ehcache.xml");
Ehcache cache = cacheManager.getCache("exampleCache");
cache.put(new Element("key1", "value1"));
System.out.println(cache.get("key1").getObjectValue()); // 輸出: value1
}
五、Spring Cache
理論介紹
Spring Cache 是 Spring 框架提供的緩存抽象層,可以與多種緩存實(shí)現(xiàn)無縫集成。它的特點(diǎn)包括:
聲明式緩存:通過注解簡(jiǎn)化緩存邏輯的實(shí)現(xiàn)。
高度集成:與 Spring 生態(tài)系統(tǒng)緊密集成,方便與其他組件協(xié)同工作。
靈活選擇:支持多種緩存提供者,如 ConcurrentMapCache、Ehcache、Caffeine 等。
實(shí)戰(zhàn)演示
pom
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.3</version>
</dependency>
yaml
spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=100,expireAfterWrite=10m
示例代碼
/**
* CacheService
* @author senfel
* @version 1.0
* @date 2024/12/20 17:45
*/
@Service
public class CacheService {
/**
* getData
* @param key
* @author senfel
* @date 2024/12/20 17:53
* @return java.lang.String
*/
@Cacheable(value = "myCache")
public String getData(String key) {
// 模擬耗時(shí)操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Value for " + key;
}
}
@Resource
private CacheService cacheService;
/**
* testCache
* @param key
* @author senfel
* @date 2024/12/20 18:00
* @return java.lang.String
*/
@RequestMapping("/testCache")
public String testCache(String key) {
return cacheService.getData(key);
}
六、總結(jié)
綜上所述,Guava Cache 簡(jiǎn)單易用,自動(dòng)回收 ,適合小型應(yīng)用,對(duì)性能要求不高;Caffeine高性能,靈活配置 高并發(fā)環(huán)境,適合對(duì)性能敏感的應(yīng)用;Ehcache功能豐富,配置靈活,適合分布式系統(tǒng),需要復(fù)雜緩存策略;Spring Cache 是聲明式緩存,高度集成 ,適合Spring 應(yīng)用,需要快速集成緩存。在實(shí)際的開放中,我們可以根據(jù)具體需求選擇合適的緩存方案,可以顯著提升應(yīng)用程序的性能和用戶體驗(yàn)。
以上就是Java實(shí)現(xiàn)本地緩存的四種方案(Guava Cache、Caffeine、Ehcach 和Spring Cache)的詳細(xì)內(nèi)容,更多關(guān)于Java本地緩存的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java JSON轉(zhuǎn)成List結(jié)構(gòu)數(shù)據(jù)
這篇文章主要介紹了Java JSON轉(zhuǎn)成List結(jié)構(gòu)數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Netty進(jìn)階之ChannelPoolMap源碼解析
這篇文章主要介紹了Netty進(jìn)階之ChannelPoolMap源碼解析,ChannelPoolMap是用來存儲(chǔ)ChannelPool和指定key的一個(gè)集合Map,實(shí)際的應(yīng)用場(chǎng)景就是服務(wù)器端是一個(gè)分布式集群服務(wù),擁有多個(gè)配置地址,這樣我們就可以配置多個(gè)服務(wù)地址,減輕單臺(tái)服務(wù)器的壓力,需要的朋友可以參考下2023-11-11
利用Jackson解析JSON的詳細(xì)實(shí)現(xiàn)教程
JSON對(duì)于開發(fā)者并不陌生,如今的WEB服務(wù)等都是以JSON作為數(shù)據(jù)交換的格式。學(xué)習(xí)JSON格式的操作工具對(duì)開發(fā)者來說是必不可少的。本文將介紹如何使用Jackson開源工具庫對(duì)JSON進(jìn)行常見操作,需要的可以參考一下2022-07-07
使用Java的Spring框架編寫第一個(gè)程序Hellow world
這篇文章主要介紹了Java的Spring框架并用其開始編寫第一個(gè)程序Hellow world的方法,Spring是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2015-12-12
MyBatis中有關(guān)int和Integer的使用方式
這篇文章主要介紹了MyBatis中有關(guān)int和Integer的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03

