Spring集成GuavaCache实现本地缓存
2024-10-19 02:19:12
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
最新文章
- UNP环境配置
- Dewplayer 音乐播放器
- 以一则LUA实例说明敏捷开发中&ldquo;分离构造和使用&rdquo;原则
- rpm安装和卸载软件
- js实现input输入框只能输入数字的功能(完美测试通过)
- TCP的那些事儿(上)
- mysql 查询技巧
- BZOJ 3997 组合数学
- linux C 管道
- eclipse内使用tomcat项目究竟被部署到了哪里
- mysql存储过程讲解
- 390. Elimination Game
- 关于mui选择器的使用
- jdk动态代理原理
- JavaScript递归原理
- Java日志-Log4j2
- 使用C#开发windows服务定时发消息到钉钉群_群组简单消息
- 【转帖】Linux定时任务Crontab命令详解
- [SQL]T-Sql 递归查询(给定节点查所有父节点、所有子节点的方法)
- Golang面向API编程-interface(接口)