
正文
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







