Spring集成GuavaCache實現本地緩存


Spring集成GuavaCache實現本地緩存:

一、SimpleCacheManager集成GuavaCache

 1 package com.bwdz.sp.comm.util.test;
 2 
 3 import com.google.common.cache.CacheBuilder;
 4 import org.springframework.cache.CacheManager;
 5 import org.springframework.cache.annotation.EnableCaching;
 6 import org.springframework.cache.guava.GuavaCache;
 7 import org.springframework.cache.support.SimpleCacheManager;
 8 import org.springframework.context.annotation.Bean;
 9 import org.springframework.context.annotation.Configuration;
10 
11 import java.util.Arrays;
12 import java.util.concurrent.TimeUnit;
13 
14 //@Configuration用於定義配置類,相當於把該類作為spring的xml配置文件,里面包含<beans>,作用為:初始化Spring容器(應用上下文)
15 //@EnableCaching注解驅動的緩存管理功能:不需要在XML文件中配置cache manager了,等價於<cache:annotation-driven/>.能夠在服務類方法上標注@Cacheable
16 //@Bean標注在方法上(返回某個實例的方法),等價於spring的xml配置文件中的<bean>,作用為:注冊bean對象
17 @Configuration
18 @EnableCaching
19 public class CacheConfig {
20     @Bean
21     public CacheManager localCacheManager() {
22         SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
23         //把各個cache注冊到cacheManager中,GuavaCache實現了org.springframework.cache.Cache接口
24         simpleCacheManager.setCaches(Arrays.asList(
25                 //CacheBuilder構建多個cache
26                 new GuavaCache(
27                         "TIMEOUT_1_HOURS",//定義cache名稱:@Cacheable的cacheNames(等價value)屬性要和此對應
28                         CacheBuilder
29                                 .newBuilder()
30                                 .expireAfterWrite(1, TimeUnit.HOURS)//參數:過期時長、單位
31                                 .build()
32                 ),
33                 new GuavaCache(
34                         "TIMEOUT_5_MINUTE",
35                         CacheBuilder
36                                 .newBuilder()
37                                 .expireAfterWrite(5, TimeUnit.MINUTES)
38                                 .build()
39                 )
40         ));
41         return simpleCacheManager;
42     }
43 }

二、集成后直接加注解使用

1     //key:緩存的 key,可以為空,如果指定要按照 SpEL 表達式編寫(當然隨便指定也不會報錯)
2     @Cacheable(cacheNames = "TIMEOUT_1_HOURS", key = "'cache_getXfshxxss'")
3     public List<Map> getXfshxxss() throws Exception {
4         return (List<Map>) dao.findForList("XxkpsjtbMapper.getXfshxxss", null);
5     }

 

1、Spring中的cache是為方法做緩存的,spring只是提供了個緩存抽象,具體的實現由第三方提供(比如guava或者自己編寫)

3、GuavaCache 支持多種緩存過期策略:定時過期、定時刷新等等

4、本地緩存:GuavaCache、ehcache、CaffeineCache,分布式緩存(網絡緩存):redis、memcached

 

https://blog.csdn.net/qq_34531925/article/details/80864773

https://segmentfault.com/a/1190000011105644

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM