Spring?Cache?集成?Caffeine實現(xiàn)項目緩存的示例
一、前言
Spring Cache本身是Spring框架中一個緩存體系的抽象實現(xiàn),本身不具備緩存能力,需要配合具體的緩存實現(xiàn)來完成,如Ehcache、Caffeine、Guava、Redis等。
二、緩存注解
- @EnableCaching:開啟緩存功能
- @Cacheable:定義緩存,用于觸發(fā)緩存
- @CachePut:定義更新緩存,觸發(fā)緩存更新
- @CacheEvict:定義清楚緩存,觸發(fā)緩存清除
- @Caching:組合定義多種緩存功能
- @CacheConfig:定義公共設(shè)置,位于class之上
三、實戰(zhàn)操作
我選擇使用目前最受歡迎的Caffeine來作為具體的緩存實現(xiàn)方式,下面是一個demo:
1、依賴引入
<dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.8.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2、yaml配置
spring: cache: cache-names: USER caffeine: spec: initialCapacity=50,maximumSize=500,expireAfterWrite=5s type: caffeine
Caffeine配置說明
- initialCapacity=[integer]: 初始的緩存空間大小
- maximumSize=[long]: 緩存的最大條數(shù)
- maximumWeight=[long]: 緩存的最大權(quán)重
- expireAfterAccess=[duration]: 最后一次寫入或訪問后經(jīng)過固定時間過期
- expireAfterWrite=[duration]: 最后一次寫入后經(jīng)過固定時間過期
- refreshAfterWrite=[duration]: 創(chuàng)建緩存或者最近一次更新緩存后經(jīng)過固定的時間間隔,刷新緩存
- weakKeys: 打開key的弱引用
- weakValues:打開value的弱引用
- softValues:打開value的軟引用
- recordStats:開發(fā)統(tǒng)計功能
注意
- expireAfterWrite和expireAfterAccess同事存在時,以expireAfterWrite為準。
- maximumSize和maximumWeight不可以同時使用
- weakValues和softValues不可以同時使用
3、開啟緩存
4、模擬方法
service層
@Service @Slf4j public class CaffeineService { public static Map<String, String> map = new HashMap<>(); static { map.put("1", "zhangsan"); map.put("2", "lisi"); map.put("3", "wangwu"); } @Cacheable(value = "USER", key = "#id") public String getUser(String id) { log.info("getUser() run......"); return map.get(id); } @CachePut(value = "USER", key = "#id") public String updateUser(String id, String name) { log.info("updateUser() run......"); map.put(id, name); return map.toString(); } @CacheEvict(value = "USER", key = "#id") public String delUser(String id) { log.info("delUser() run......"); map.remove(id); return map.toString(); } }
controller層
@RestController @RequestMapping("/cache") @Slf4j public class CaffeineController { @Autowired private CaffeineService caffeineService; @GetMapping("/user/{id}") public String getUser(@PathVariable String id) { long start = System.currentTimeMillis(); String res = caffeineService.getUser(id); long end = System.currentTimeMillis(); log.info("查詢耗時:" + (end - start)); return res; } @GetMapping("/user/{id}/{name}") public String updateUser(@PathVariable String id, @PathVariable String name) { return caffeineService.updateUser(id, name); } @DeleteMapping("/user/{id}") public String delUser(@PathVariable String id) { return caffeineService.delUser(id); } }
5、測試
第一次查詢:
第二次查詢:
查詢耗時明顯小于第一次查詢,因為第二次直接返回緩存,速度提升。
執(zhí)行更新后再查詢:
會使緩存失效。會重新執(zhí)行查詢方法查詢
執(zhí)行刪除后再查詢:
會使緩存失效。會重新執(zhí)行查詢方法查詢
6、改造
上述通過yaml文件配置的方式不夠靈活,無法實現(xiàn)多種緩存策略,所以現(xiàn)在一般使用javaconfig的形式進行配置。
下面是示例代碼:
@Configuration public class CaffeineConfig { @Bean public CacheManager caffeineCacheManager() { SimpleCacheManager simpleCacheManager = new SimpleCacheManager(); List<CaffeineCache> caffeineCaches = new ArrayList<>(); for (CacheType cacheType : CacheType.values()) { caffeineCaches.add(new CaffeineCache(cacheType.name(), Caffeine.newBuilder() .expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS) .build())); } simpleCacheManager.setCaches(caffeineCaches); return simpleCacheManager; } }
public enum CacheType { USER(5), TENANT(20); private int expires; CacheType(int expires) { this.expires = expires; } public int getExpires() { return expires; } }
這樣我們就能對USER設(shè)置5秒消防時間,對TENANT設(shè)置20秒消亡時間,在實際項目中這種方式更加的靈活。
到此這篇關(guān)于Spring Cache 集成 Caffeine實現(xiàn)項目緩存的示例的文章就介紹到這了,更多相關(guān)Spring Cache Caffeine緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java獲取系統(tǒng)路徑字體、得到某個目錄下的所有文件名、獲取當前路徑
這篇文章主要介紹了java獲取系統(tǒng)路徑字體、得到某個目錄下的所有文件名、獲取當前路徑,需要的朋友可以參考下2014-04-04IntelliJ IDEA基于Scala實現(xiàn)Git檢查工具
這篇文章主要介紹了如何使用Scala實現(xiàn)自定義的Git檢查工具,大家可以基于本文的示例進行擴展與實現(xiàn),也可以進行其他應用方向的嘗試,感興趣的可以了解下2023-08-08基于selenium-java封裝chrome、firefox、phantomjs實現(xiàn)爬蟲
這篇文章主要介紹了基于selenium-java封裝chrome、firefox、phantomjs實現(xiàn)爬蟲,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2020-10-10IntelliJ?IDEA?2022.2.3最新激活圖文教程(親測有用永久激活)
今天給大家分享一個?IDEA?2022.2.3?的激活破解教程,全文通過文字+圖片的方式講解,手把手教你如何激活破解?IDEA,?只需要幾分鐘即可搞定,對idea2022.2.3激活碼感興趣的朋友跟隨小編一起看看吧2022-11-11