Java中本地緩存的4種實現(xiàn)方式總結
前言
在Java開發(fā)中,緩存技術是提高應用性能的關鍵手段之一。
今天,我們來聊聊Java中的四種主流本地緩存技術,并通過實例代碼幫助大家更好地理解和應用這些技術。
一、基礎緩存實現(xiàn)
首先,我們從最基礎的緩存實現(xiàn)講起。
一個簡單的緩存系統(tǒng)通常包括緩存實體類、添加、刪除、查詢和清除緩存的功能。
1. 緩存實體類
緩存實體類用于存儲緩存的鍵值對以及過期時間。
代碼如下:。
public class CacheEntity {
private String cacheKey;
private Object cacheValue;
private long expireTime; // 過期時間戳
// 構造方法、getter和setter省略
}2. 緩存工具類
接下來,我們實現(xiàn)一個緩存工具類,使用ConcurrentHashMap作為存儲結構,并通過定時任務清除過期數(shù)據(jù)。
import java.util.concurrent.*;
import java.util.Map;
publicclassCacheUtil {
privatefinalstatic Map<String, CacheEntity> CACHE_MAP = newConcurrentHashMap<>();
privatestaticScheduledExecutorServiceexecutorService= Executors.newSingleThreadScheduledExecutor();
static {
executorService.scheduleAtFixedRate(() -> {
longcurrentTime= System.currentTimeMillis();
CACHE_MAP.values().removeIf(entity -> entity.getExpireTime() < currentTime);
}, 0, 500, TimeUnit.MILLISECONDS);
}
publicstaticvoidput(String key, Object value, long expireTimeInSeconds) {
longexpireTime= System.currentTimeMillis() + expireTimeInSeconds * 1000;
CACHE_MAP.put(key, newCacheEntity(key, value, expireTime));
}
publicstatic Object get(String key) {
CacheEntityentity= CACHE_MAP.get(key);
if (entity == null || entity.getExpireTime() < System.currentTimeMillis()) {
CACHE_MAP.remove(key);
returnnull;
}
return entity.getCacheValue();
}
publicstaticvoiddelete(String key) {
CACHE_MAP.remove(key);
}
publicstaticvoidclear() {
CACHE_MAP.clear();
}
}測試代碼:
public class Test {
public static void main(String[] args) throws InterruptedException {
CacheUtil.put("name", "zzc", 10L);
System.out.println("第一次查詢結果:" + CacheUtil.get("name"));
Thread.sleep(2000L);
System.out.println("第二次查詢結果:" + CacheUtil.get("name"));
}
}二、Guava LoadingCache
Guava是Google提供的一個Java基礎庫,其中的LoadingCache是一個強大的緩存工具。
1. 使用示例
import com.google.common.cache.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
publicclassTest {
publicstaticvoidmain(String[] args)throws ExecutionException {
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.concurrencyLevel(8)
.expireAfterWrite(10, TimeUnit.SECONDS)
.build(newCacheLoader<String, String>() {
@Override
public String load(String key)throws Exception {
return"default_value";
}
});
cache.put("name", "zzc");
StringnameValue= cache.get("name");
StringageValue= cache.get("age", () -> "default_age");
StringsexValue= cache.get("sex", () -> "key 不存在");
System.out.println("nameValue: " + nameValue);
System.out.println("ageValue: " + ageValue);
System.out.println("sexValue: " + sexValue);
}
}在上面的代碼中,當調(diào)用cache.get(key)方法時,如果緩存中不存在對應的key,則會通過CacheLoader的load方法加載默認值。
三、SpringBoot整合Caffeine
Caffeine是一個高性能的Java緩存庫,SpringBoot提供了與Caffeine的無縫整合。
1. 開啟緩存功能
在啟動類上添加@EnableCaching注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}2. 配置緩存管理器
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
publicclassCacheConfig {
@Bean("caffeineCacheManager")
public CacheManager cacheManager() {
CaffeineCacheManagercacheManager=newCaffeineCacheManager("userCache");
cacheManager.getCache("userCache").getConfig().setCaffeine(caffeineCacheBuilder());
return cacheManager;
}
Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.maximumSize(100);
}
}3. 使用緩存注解
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
publicclassUserService {
// 模擬數(shù)據(jù)庫操作
private Map<Integer, User> userMap = newHashMap<>();
@Cacheable(value = "userCache", key = "#id")
public User getUserById(Integer id) {
// 假設從數(shù)據(jù)庫獲取用戶數(shù)據(jù)
Useruser=newUser();
user.setId(id);
user.setName("User" + id);
userMap.put(id, user);
return user;
}
@CacheEvict(value = "userCache", key = "#id")
publicvoiddeleteUserById(Integer id) {
userMap.remove(id);
}
}四、JetCache——阿里巴巴的分布式緩存框架
JetCache是阿里巴巴開源的一款基于Spring和Redis的分布式緩存框架,提供了強大的緩存抽象和注解支持。
1. 引入依賴
在pom.xml中添加JetCache依賴。
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>最新版本號</version>
</dependency>2. 配置JetCache
在application.yml中配置JetCache。
jetcache:
stat:enable# 開啟統(tǒng)計
remote:
default:
type:redis
keyConvertor:fastjson# 序列化方式
valueEncoder:java
valueDecoder:java
poolConfig:
minIdle:5
maxIdle:20
maxTotal:50
host:localhost
port: 63793. 使用JetCache注解
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.CacheInvalidate;
import org.springframework.stereotype.Service;
@Service
publicclassUserService {
@Cached(name = "userCache", key = "#id", cacheType = CacheType.BOTH)
public String getUser(int id) {
return"用戶:" + id;
}
@CacheUpdate(name = "userCache", key = "#id", value = "#user")
publicvoidupdateUser(int id, String user) {
System.out.println("更新用戶:" + user);
}
@CacheInvalidate(name = "userCache", key = "#id")
publicvoiddeleteUser(int id) {
System.out.println("刪除用戶:" + id);
}
}JetCache支持本地緩存和遠程緩存的組合,非常適合分布式系統(tǒng)。
總結
今天我們一起探索了Java本地緩存的多種實現(xiàn)方式,從手寫緩存到Guava Cache、Caffeine、Ehcache和JetCache。每種方式都有自己的特點和適用場景。
到此這篇關于Java中本地緩存的4種實現(xiàn)方式的文章就介紹到這了,更多相關Java本地緩存實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Cloud實現(xiàn)微服務調(diào)用的負載均衡(詳解)
負載均衡就是將負載(工作任務,訪問請求)進行分攤到多個操作單元(服務器,組件)上進行執(zhí)行,根據(jù)負載均衡發(fā)生位置的不同,一般分為服務端負載均衡和客戶端負載均衡,本文給大家介紹Spring Cloud實現(xiàn)微服務調(diào)用的負載均衡的相關知識,感興趣的朋友一起看看吧2024-03-03
解決新版 Idea 中 SpringBoot 熱部署不生效的問題
這篇文章主要介紹了解決新版 Idea 中 SpringBoot 熱部署不生效的問題,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
Java利用Spire.XLS for Java實現(xiàn)在Excel文件中添加或刪除分節(jié)符
在復雜的Excel報表中,合理設置分節(jié)符能有效提升文檔結構與可讀性,尤其在打印輸出時效果顯著,本文將深入探討如何利用Spire.XLS for Java輕松實現(xiàn)Excel分節(jié)符的添加與刪除,希望對大家有所幫助2025-11-11
springboot 配置文件配置項前綴為0的數(shù)字特殊處理方式
這篇文章主要介紹了springboot 配置文件配置項前綴為0的數(shù)字特殊處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
IntelliJ IDEA編譯提速的兩種配置指南(中性能&高性能)
很多開發(fā)者發(fā)現(xiàn),明明電腦配置挺高,IDEA 編譯 Maven 項目依然卡,本文帶大家從原理到實戰(zhàn),提供 兩套可直接復制使用的 VM 參數(shù)方案,有需要的小伙伴可以了解下2025-10-10

