SpringBoot集成Caffeine緩存的實(shí)現(xiàn)步驟
要開始使用咖啡因Caffeine和Spring Boot,我們首先添加spring-boot-starter-cache和咖啡因Caffeine依賴項(xiàng):
<dependencies> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId> </dependency></dependencies>
這些將導(dǎo)入基本Spring緩存支持,以及Caffeine庫(kù)。
配置現(xiàn)在我們需要在Spring Boot應(yīng)用程序中配置緩存。
首先,我們制造一種Caffeine bean。這是控制緩存行為(如過期、緩存大小限制等)的主要配置:
@Beanpublic Caffeine caffeineConfig() { return Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES);}
接下來,我們需要使用Spring CacheManager接口創(chuàng)建另一個(gè)bean。Caffeine提供了這個(gè)接口的實(shí)現(xiàn),它需要我們?cè)谏厦鎰?chuàng)建的咖啡因?qū)ο螅?/p>
@Beanpublic CacheManager cacheManager(Caffeine caffeine) { CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager(); caffeineCacheManager.setCaffeine(caffeine); return caffeineCacheManager;}
最后,我們需要使用@EnableCaching注釋在springboot中啟用緩存。這可以添加到應(yīng)用程序中的任何@Configuration類中。
示例在啟用緩存并配置為使用咖啡因的情況下,讓我們看看如何在SpringBoot應(yīng)用程序中使用緩存的幾個(gè)示例。
在SpringBoot中使用緩存的主要方法是使用@Cacheable注釋。這個(gè)注釋適用于SpringBean的任何方法(甚至整個(gè)類)。它指示注冊(cè)的緩存管理器將方法調(diào)用的結(jié)果存儲(chǔ)在緩存中。
典型的用法是服務(wù)類內(nèi)部:
@Servicepublic class AddressService { @Cacheable public AddressDTO getAddress(long customerId) {// lookup and return result }}
使用不帶參數(shù)的@Cacheable注釋將強(qiáng)制Spring為cache和cache鍵使用默認(rèn)名稱。
我們可以通過向注釋中添加一些參數(shù)來覆蓋這兩種行為:
@Servicepublic class AddressService { @Cacheable(value = 'address_cache', key = 'customerId') public AddressDTO getAddress(long customerId) {// lookup and return result }}
上面的例子告訴Spring使用名為address_cache的緩存和customerId參數(shù)作為緩存鍵。
最后,由于緩存管理器本身就是一個(gè)SpringBean,我們還可以將它自動(dòng)連接到任何其他bean中并直接使用它:
@Servicepublic class AddressService { @Autowired CacheManager cacheManager; public AddressDTO getAddress(long customerId) {if(cacheManager.containsKey(customerId)) { return cacheManager.get(customerId);}// lookup address, cache result, and return it }}
完整代碼地址:https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-libraries
以上就是SpringBoot集成Caffeine緩存的步驟的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot集成Caffeine緩存的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)2. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車輛管理系統(tǒng)3. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. Jsp servlet驗(yàn)證碼工具類分享6. jscript與vbscript 操作XML元素屬性的代碼7. 基于PHP做個(gè)圖片防盜鏈8. Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)9. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解10. XML在語音合成中的應(yīng)用
