Java高性能緩存框架之Caffeine詳解
Caffeine緩存框架
Caffeine是一個基于Java8的高性能緩存框架,號稱趨于完美。
Caffeine受啟發(fā)于Guava Cache的API,使用API和Guava是一致的。
它借鑒了Guava Cache和ConcurrentLinkedHashMap的設(shè)計經(jīng)驗。
在Springboot中使用Caffeine
在工程的pom文件引入caffeine的依賴,如下:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.6.2</version>
</dependency>創(chuàng)建一個抽象類AbstractCaffineCache,該類使用范型來約束緩存的數(shù)據(jù)類型,并實現(xiàn)了三個方法,put、get、clear。
/**
* @Author ZhuZiKai
* @Description
* @date 2022/3/7 10:44
*/
public abstract class AbstractCaffeineCache<T> {
protected LoadingCache<String, T> loadingCache;
abstract LoadingCache<String, T> createLoadingCache();
public boolean put(String key, T value) {
if (loadingCache == null) {
loadingCache = createLoadingCache();
}
loadingCache.put(key, value);
return Boolean.TRUE;
}
public T get(String key) {
if (loadingCache == null) {
loadingCache = createLoadingCache();
}
try {
return loadingCache.get(key);
} catch (Exception e) {
return null;
}
}
public boolean clear(String key) {
if (loadingCache == null) {
loadingCache = createLoadingCache();
}
loadingCache.invalidate(key);
return Boolean.TRUE;
}
}創(chuàng)建MyCaffeineCache的緩存類,該類緩存類。創(chuàng)建LoadingCache類,該類設(shè)置了緩存過期的時間,最大的緩存?zhèn)€數(shù)。
/**
* @Author ZhuZiKai
* @Description
* @date 2022/3/7 10:44
*/
public class MyCaffeineCache extends AbstractCaffeineCache {
/**
* Caffeine配置說明:
* initialCapacity=[integer]: 初始的緩存空間大小
* maximumSize=[long]: 緩存的最大條數(shù)
* maximumWeight=[long]: 緩存的最大權(quán)重
* expireAfterAccess=[duration]: 最后一次寫入或訪問后經(jīng)過固定時間過期
* expireAfterWrite=[duration]: 最后一次寫入后經(jīng)過固定時間過期
* refreshAfterWrite=[duration]: 創(chuàng)建緩存或者最近一次更新緩存后經(jīng)過固定的時間間隔,刷新緩存
* recordStats:開發(fā)統(tǒng)計功能
*
* @return
*/
@Override
LoadingCache createLoadingCache() {
loadingCache = Caffeine.newBuilder()
.expireAfterWrite(1000L, TimeUnit.MILLISECONDS)
.initialCapacity(10)
.maximumSize(100)
.recordStats()
.build((CacheLoader<String, String>) key -> null);
return loadingCache;
}
}將MyCaffeineCache注入到spring ioc中,代碼如下:
/**
* @Author ZhuZiKai
* @Description
* @date 2022/3/7 10:45
*/
@Configuration
public class CaffeineCacheConfig {
@Bean
public MyCaffeineCache MyCaffeineCache(){
return new MyCaffeineCache();
}
}如何使用。
/**
* @Author ZhuZiKai
* @Description
* @date 2022/1/6 9:45
*/
@Aspect
@Component
@Slf4j
public class IdempotentAspect extends BaseController {
@Resource
private MyCaffeineCache cache;
private static final ThreadLocalUtil threadLocalUtil = new ThreadLocalUtil();
@Around(value = "@annotation(idempotent)")
public Object around(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {
UserBO user = getUserBO(request);
Integer userId = user.getUserId();
String userRequest = userId + request.getRequestURI();
threadLocalUtil.setLocalUserRequest(userRequest);
Object uuid = cache.get(userRequest);
VerifyUtils.throwWhen(uuid != null, idempotent.value());
return joinPoint.proceed();
}
@AfterReturning(value = "@annotation(idempotent)")
public void afterReturning(JoinPoint point, Idempotent idempotent) {
try {
cache.put(threadLocalUtil.getLocalUserRequest(), UUIDUtil.simpleUUID());
} finally {
threadLocalUtil.clearLocalUserRequest();
}
}
}使用本地緩存可以加快頁面響應(yīng)速度,緩存分布式緩存讀壓力,大量、高并發(fā)請求的網(wǎng)站比較適用
Caffeine配置說明:
- initialCapacity=[integer]: 初始的緩存空間大小
- maximumSize=[long]: 緩存的最大條數(shù)
- maximumWeight=[long]: 緩存的最大權(quán)重
- expireAfterAccess=[duration]: 最后一次寫入或訪問后經(jīng)過固定時間過期
- expireAfterWrite=[duration]: 最后一次寫入后經(jīng)過固定時間過期
- refreshAfterWrite=[duration]: 創(chuàng)建緩存或者最近一次更新緩存后經(jīng)過固定的時間間隔,刷新緩存
- recordStats:開發(fā)統(tǒng)計功能
注意: expireAfterWrite和expireAfterAccess同時存在時,以expireAfterWrite為準(zhǔn)。
到此這篇關(guān)于Java高性能緩存框架之Caffeine詳解的文章就介紹到這了,更多相關(guān)緩存框架Caffeine內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring-gateway filters添加自定義過濾器實現(xiàn)流程分析(可插拔)
這篇文章主要介紹了spring-gateway filters添加自定義過濾器實現(xiàn)流程分析(可插拔),本文通過實例圖文相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2025-05-05
Java設(shè)計模式之工廠模式實現(xiàn)方法詳解
這篇文章主要介紹了Java設(shè)計模式之工廠模式實現(xiàn)方法,結(jié)合實例形式較為詳細(xì)的分析了工廠模式的分類、原理、實現(xiàn)方法與相關(guān)注意事項,需要的朋友可以參考下2017-12-12
jdk配置完之后java?-version還是默認(rèn)的jdk版本問題解決過程
在CentOS7中配置JDK后,java?-version仍顯示默認(rèn)JDK,因為系統(tǒng)默認(rèn)的/usr/bin/java軟鏈接優(yōu)先級高于PATH環(huán)境變量,這篇文章主要介紹了jdk配置完之后java?-version還是默認(rèn)的jdk版本問題的解決過程,需要的朋友可以參考下2026-01-01
SpringBoot+mybatis-plus實現(xiàn)多數(shù)據(jù)源配置(開箱即用)
本文介紹了dynamic-datasource-spring-boot-starter,一個用于快速集成多數(shù)據(jù)源的Spring Boot啟動器,它支持多種數(shù)據(jù)源配置、分組、加密、初始化表結(jié)構(gòu)、懶加載等特性,并提供了對多種數(shù)據(jù)庫和組件的集成方案,感興趣的朋友跟隨小編一起看看吧2025-12-12

