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

最新文章

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

热门文章

  1. Salesforce LWC学习(二十九) getRecordNotifyChange(LDS拓展增强篇)
  2. [日常摸鱼]POJ2187 BeautyContest-旋转卡壳
  3. TP学习—第一天:框架的简单学习;创建应用;
  4. Python利用pandas处理数据后画图
  5. 写一个nginx.conf方便用于下载某个网页的所有资源
  6. 基于LNMP架构搭建wordpress博客之安装架构说明
  7. ES标签搜索并解决评分排序问题
  8. Android猜数字大小游戏
  9. Java学习日报7.31
  10. 冒泡排序算法JAVA实现版