Spring?Cache?集成?Caffeine實(shí)現(xiàn)項(xiàng)目緩存的示例
一、前言
Spring Cache本身是Spring框架中一個(gè)緩存體系的抽象實(shí)現(xiàn),本身不具備緩存能力,需要配合具體的緩存實(shí)現(xiàn)來(lái)完成,如Ehcache、Caffeine、Guava、Redis等。
二、緩存注解
- @EnableCaching:開(kāi)啟緩存功能
- @Cacheable:定義緩存,用于觸發(fā)緩存
- @CachePut:定義更新緩存,觸發(fā)緩存更新
- @CacheEvict:定義清楚緩存,觸發(fā)緩存清除
- @Caching:組合定義多種緩存功能
- @CacheConfig:定義公共設(shè)置,位于class之上
三、實(shí)戰(zhàn)操作
我選擇使用目前最受歡迎的Caffeine來(lái)作為具體的緩存實(shí)現(xiàn)方式,下面是一個(gè)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配置說(shuō)明
- initialCapacity=[integer]: 初始的緩存空間大小
- maximumSize=[long]: 緩存的最大條數(shù)
- maximumWeight=[long]: 緩存的最大權(quán)重
- expireAfterAccess=[duration]: 最后一次寫(xiě)入或訪問(wèn)后經(jīng)過(guò)固定時(shí)間過(guò)期
- expireAfterWrite=[duration]: 最后一次寫(xiě)入后經(jīng)過(guò)固定時(shí)間過(guò)期
- refreshAfterWrite=[duration]: 創(chuàng)建緩存或者最近一次更新緩存后經(jīng)過(guò)固定的時(shí)間間隔,刷新緩存
- weakKeys: 打開(kāi)key的弱引用
- weakValues:打開(kāi)value的弱引用
- softValues:打開(kāi)value的軟引用
- recordStats:開(kāi)發(fā)統(tǒng)計(jì)功能
注意
- expireAfterWrite和expireAfterAccess同事存在時(shí),以expireAfterWrite為準(zhǔn)。
- maximumSize和maximumWeight不可以同時(shí)使用
- weakValues和softValues不可以同時(shí)使用
3、開(kāi)啟緩存
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("查詢耗時(shí):" + (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、測(cè)試
第一次查詢:
第二次查詢:
查詢耗時(shí)明顯小于第一次查詢,因?yàn)榈诙沃苯臃祷鼐彺妫俣忍嵘?/p>
執(zhí)行更新后再查詢:
會(huì)使緩存失效。會(huì)重新執(zhí)行查詢方法查詢
執(zhí)行刪除后再查詢:
會(huì)使緩存失效。會(huì)重新執(zhí)行查詢方法查詢
6、改造
上述通過(guò)yaml文件配置的方式不夠靈活,無(wú)法實(shí)現(xiàn)多種緩存策略,所以現(xiàn)在一般使用javaconfig的形式進(jìn)行配置。
下面是示例代碼:
@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; } }
這樣我們就能對(duì)USER設(shè)置5秒消防時(shí)間,對(duì)TENANT設(shè)置20秒消亡時(shí)間,在實(shí)際項(xiàng)目中這種方式更加的靈活。
到此這篇關(guān)于Spring Cache 集成 Caffeine實(shí)現(xiàn)項(xiàng)目緩存的示例的文章就介紹到這了,更多相關(guān)Spring Cache Caffeine緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java獲取系統(tǒng)路徑字體、得到某個(gè)目錄下的所有文件名、獲取當(dāng)前路徑
這篇文章主要介紹了java獲取系統(tǒng)路徑字體、得到某個(gè)目錄下的所有文件名、獲取當(dāng)前路徑,需要的朋友可以參考下2014-04-04IntelliJ IDEA基于Scala實(shí)現(xiàn)Git檢查工具
這篇文章主要介紹了如何使用Scala實(shí)現(xiàn)自定義的Git檢查工具,大家可以基于本文的示例進(jìn)行擴(kuò)展與實(shí)現(xiàn),也可以進(jìn)行其他應(yīng)用方向的嘗試,感興趣的可以了解下2023-08-08Java變態(tài)跳臺(tái)階實(shí)現(xiàn)思路和代碼
今天小編就為大家分享一篇關(guān)于Java變態(tài)跳臺(tái)階實(shí)現(xiàn)思路和代碼,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01Spring中@Transactional用法詳細(xì)介紹
這篇文章主要介紹了Spring中@Transactional用法詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-02-02基于selenium-java封裝chrome、firefox、phantomjs實(shí)現(xiàn)爬蟲(chóng)
這篇文章主要介紹了基于selenium-java封裝chrome、firefox、phantomjs實(shí)現(xiàn)爬蟲(chóng),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2020-10-10IntelliJ?IDEA?2022.2.3最新激活圖文教程(親測(cè)有用永久激活)
今天給大家分享一個(gè)?IDEA?2022.2.3?的激活破解教程,全文通過(guò)文字+圖片的方式講解,手把手教你如何激活破解?IDEA,?只需要幾分鐘即可搞定,對(duì)idea2022.2.3激活碼感興趣的朋友跟隨小編一起看看吧2022-11-11