springboot整合guava實現(xiàn)本地緩存的示例代碼
一、Springboot緩存
SpringBoot支持很多種緩存方式:redis、guava、ehcahe、jcache等等。
二、guava介紹
Guava Cache 是 Google 開源的一套開發(fā)工具集合,Guava Cache 是其中的一個專門用于處理本地緩存的輕量級框架,是全內(nèi)存方式的本地緩存,而且是線程安全的。
和 ConcurrentMap 相比,Guava Cache 可以限制內(nèi)存的占用,并可設(shè)置緩存的過期時間,可以自動回收數(shù)據(jù),而 ConcurrentMap 只能通過靜態(tài)方式來控制緩存,移除數(shù)據(jù)元素需要顯示的方式來移除。
三、 緩存回收方式
1、基于容量回收

2、基于時間回收

3、基于引用回收
CacheBuilder.weakValues():和 CacheBuilder.weakKeys() 方法類似,該方法按照弱引用方式來存儲緩存項的值,允許系統(tǒng)垃圾回收時回收緩存項。
CacheBuilder.weakValues(),使用軟引用方式來包裝緩存值,只有在內(nèi)存需要時(一般在接近內(nèi)存溢出時),系統(tǒng)會按照全局LRU(least-recently-used)原則進行垃圾回收??紤]到垃圾回收的性能問題,推薦使用基于容量的回收方式。
4、手動回收

guava使用
導(dǎo)入依賴
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>recordStats:開啟統(tǒng)計功能
stats:查看統(tǒng)計情況
void testRecordStats(){
Cache<String, String> callCache = CacheBuilder.newBuilder().
initialCapacity(5)
.maximumSize(100)
.recordStats()
.expireAfterAccess(1, TimeUnit.SECONDS)
.build();
/**
* CacheStats{hitCount=0, missCount=0, loadSuccessCount=0, loadExceptionCount=0, totalLoadTime=0, evictionCount=0}
*/
CacheStats stats = callCache.stats();
System.out.println(stats);
}
并發(fā)級別
調(diào)整concurrencyLevel即可

5、代碼實例
/**
* @Author sprem至尊
* @Date 2022/10/24 19:39
* @Version 1.0
*/
package com.cn.xiaonuo.modular.wechat.cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class TokenCache {
private static LoadingCache<String,String> loadingCache = CacheBuilder
.newBuilder().initialCapacity(100).maximumSize(100)
.expireAfterWrite(7000, TimeUnit.SECONDS)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return null;
}
});
public static void setKey(String key,String value){
loadingCache.put(key, value);
}
public static String getValue(String key){
String value = null;
try{
value = loadingCache.get(key);
if(value == null){
return null;
}
return value;
}catch (Exception e){
return null;
}
}
}到此這篇關(guān)于springboot整合guava實現(xiàn)本地緩存的示例代碼的文章就介紹到這了,更多相關(guān)springboot guava本地緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
maven異常Invalid?bound?statement(not?found)的問題解決
本文詳細介紹了Maven項目中常見的Invalidboundstatement異常及其解決方案,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-12-12
Java和MySQL數(shù)據(jù)庫中關(guān)于小數(shù)的保存問題詳析
在Java和MySQL中小數(shù)的精度可能會受到限制,如float類型的小數(shù)只能精確到6-7位,double類型也只能精確到15-16位,這篇文章主要給大家介紹了關(guān)于Java和MySQL數(shù)據(jù)庫中關(guān)于小數(shù)的保存問題,需要的朋友可以參考下2024-01-01
Java實現(xiàn)學(xué)生信息管理系統(tǒng)IO版本
這篇文章主要為大家詳細介紹了Java實現(xiàn)學(xué)生信息管理系統(tǒng)IO版本,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04
Java 1,2,3,4能組成多少個互不相同且無重復(fù)數(shù)字的實現(xiàn)代碼
這篇文章主要介紹了Java 1,2,3,4能組成多少個互不相同且無重復(fù)數(shù)字的實現(xiàn)代碼,需要的朋友可以參考下2017-02-02

