Spring Boot 揭秘与实战(二) 数据缓存篇 - Guava Cache

文章目录

  1. 1. Guava Cache 集成
  2. 2. 个性化配置
  3. 3. 源代码

本文,讲解 Spring Boot 如何集成 Guava Cache,实现缓存。

在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门」后,对 Spring Boot 集成缓存机制有一定了解后,对 Spring Boot 集成缓存机制有一定了解后,我们来了解下 Guava Cache 的使用。

Guava Cache 集成

Guava 包含了若干被 Google 的 Java 项目广泛依赖的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] 、字符串处理 [string processing] 、I/O 等等。

题外话,个人对 Guava 的 集合 [collections] 、缓存 [caching] 十分钟爱。

Spring Boot 对 Guava 的缓存机制也做了很好的支持。

在 Spring Boot 中集成 Guava Cache 非常容易,只需要在 pom.xml 中增加Guava 依赖即可。

  1. <dependency>
  2. <groupId>com.google.guava</groupId>
  3. <artifactId>guava</artifactId>
  4. <version>19.0</version>
  5. </dependency>

其实,底层根据自动配置机制实现的。具体实现原理,如果有兴趣的话,可以参考之前的文章「Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机」 和 「Spring Boot 揭秘与实战 源码分析 - 工作原理剖析」。

如果想对 Guava Cache 更深入的了解,可以参考 http://ifeve.com/google-guava-cachesexplained/。

运行起来,控制台打印的日志信息,说明已经是 GuavaCacheManager 实例,说明 GuavaCache 开启成功了。

  1. Bean 'cacheManager' of type [class org.springframework.cache.guava.GuavaCacheManager]

个性化配置

如果想自定义参数,例如存活时间,缓存最大数目等。我们可以通过 Java Config 的方式,进行配置。

下面案例,我配置存活时间为 10 秒,缓存最大数目为 1000 个。

  1. @Configuration
  2. @EnableCaching
  3. public class GuavaCacheConfig {
  4. @Bean
  5. public CacheManager cacheManager() {
  6. GuavaCacheManager cacheManager = new GuavaCacheManager();
  7. cacheManager.setCacheBuilder(
  8. CacheBuilder.newBuilder().
  9. expireAfterWrite(10, TimeUnit.SECONDS).
  10. maximumSize(1000));
  11. return cacheManager;
  12. }
  13. }

源代码

相关示例完整代码: springboot-action

(完)

 

微信公众号

转载于:https://www.cnblogs.com/cnblog-long/p/7243014.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值