Java中Caffeine本地緩存項目實例
前言
為什么需要本地緩存?在系統(tǒng)中,有些數(shù)據(jù),訪問十分頻繁(例如數(shù)據(jù)字典數(shù)據(jù)、國家標準行政區(qū)域數(shù)據(jù)),往往把這些數(shù)據(jù)放入分布式緩存中,但為了減少網(wǎng)絡傳輸,加快響應速度,緩存分布式緩存讀壓力,會把這些數(shù)據(jù)緩存到本地JVM中,大多是先取本地緩存中,再取分布式緩存中的數(shù)據(jù)
而Caffeine是一個高性能Java 緩存庫,使用Java8對Guava緩存重寫版本,在Spring Boot 2.0中將取代Guava。 使用spring.cache.cache-names屬性可以在啟動時創(chuàng)建緩存
例如,以下application配置創(chuàng)建一個foo和bar緩存,最大數(shù)量為500,存活時間為10分鐘
spring.cache.cache-names=foo,bar spring.cache.caffeine.spec=initialCapacity=10,maximumSize=500,expireAfterAccess=600s
還有一種代碼實現(xiàn)方式,我在項目中就是使用代碼方式,如何使用,請往下看
代碼實現(xiàn)
1.引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.6.2</version> </dependency>
2.添加一個CaffeineConfig配置類,開啟緩存@EnableCaching
@Configuration
@EnableCaching //開啟緩存
public class CaffeineConfig {
public static final int DEFAULT_MAXSIZE = 10000;
public static final int DEFAULT_TTL = 600;
/**
* 定義cache名稱、超時時長(秒)、最大容量
* 每個cache缺?。?0秒超時、最多緩存50000條數(shù)據(jù),需要修改可以在構(gòu)造方法的參數(shù)中指定。
*/
public enum Caches{
getUserById(600), //有效期600秒
listCustomers(7200,1000), //有效期2個小時 , 最大容量1000
;
Caches() {
}
Caches(int ttl) {
this.ttl = ttl;
}
Caches(int ttl, int maxSize) {
this.ttl = ttl;
this.maxSize = maxSize;
}
private int maxSize=DEFAULT_MAXSIZE; //最大數(shù)量
private int ttl=DEFAULT_TTL; //過期時間(秒)
public int getMaxSize() {
return maxSize;
}
public int getTtl() {
return ttl;
}
}
/**
* 創(chuàng)建基于Caffeine的Cache Manager
* @return
*/
@Bean
@Primary
public CacheManager caffeineCacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
ArrayList<CaffeineCache> caches = new ArrayList<CaffeineCache>();
for(Caches c : Caches.values()){
caches.add(new CaffeineCache(c.name(),
Caffeine.newBuilder().recordStats()
.expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
.maximumSize(c.getMaxSize())
.build())
);
}
cacheManager.setCaches(caches);
return cacheManager;
}
}3.創(chuàng)建控制器
創(chuàng)建一個控制器,使用本地緩存,注意@Cacheable,value與上面配置的值對應,key為參數(shù),sync=true表示同步,多個請求會被阻塞
@RestController
@RequestMapping("cache")
public class CacheController {
@RequestMapping("listCustomers")
@Cacheable( value = "listCustomers" , key = "#length", sync = true)
public List<Customer> listCustomers(Long length){
List<Customer> customers = new ArrayList<>();
for(int i=1; i <= length ; i ++){
Customer customer = new Customer(i, "zhuyu"+i, 20 + i, false);
customers.add(customer);
}
return customers;
}
// 以第一個參數(shù)為key進行緩存
@Cacheable(value="users", key="#p0")
public Long find(Long id) {
return id;
}
// 以User中的id值為key進行緩存
@Cacheable(value="users", key="#user.id")
public User find(User user) {
return user;
}
// 以User中的id值為key,且 condition 條件滿足則緩存
@Cacheable(value="users", key="#user.id", condition="#user.id%2==0")
public User find(User user) {
return user;
}
}- @CacheEvict 是用來標注清除緩存元素的,可在方法或類上。當標記在一個類上表示其中所有的方法的執(zhí)行都會觸發(fā)緩存的清除操作。
- @CacheEvict可以指定的屬性有value、key、condition、allEntries和beforeInvocation。其中value、key和condition的語義與@Cacheable對應的屬性類似。即value表示清除操作是發(fā)生在哪些Cache上的(對應Cache的名稱);key表示需要清除的是哪個key,如未指定則會使用默認策略生成的key;condition表示清除操作發(fā)生的條件
// allEntries表示是否需要清除緩存中的所有元素。默認為false,當allEntries為true時,清除所有的元素
@CacheEvict(value="user", allEntries=true)
public void delete(Integer id) {
System.out.println(id);
}4.啟動項目
訪問上面的方法,效果如下,第一次處理時間為 110ms ,再刷新幾次頁面只要 1ms,說明后面的請求從本地緩存中獲取數(shù)據(jù),并返回了


使用本地緩存可以加快頁面響應速度,緩存分布式緩存讀壓力,大量、高并發(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為準。
- maximumSize和maximumWeight不可以同時使用
到此這篇關于Java中Caffeine本地緩存項目實例的文章就介紹到這了,更多相關Caffeine本地緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot自動配置原理以及spring.factories文件的作用詳解
這篇文章主要介紹了springboot自動配置原理以及spring.factories文件的作用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
SpringBoot?實現(xiàn)動態(tài)添加定時任務功能
這篇文章主要介紹了SpringBoot?動態(tài)添加定時任務,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02
Java后臺返回和處理JSon數(shù)據(jù)的方法步驟
這篇文章主要介紹了Java后臺返回和處理JSon數(shù)據(jù)的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09

