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

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

博客地址:blog.720ui.com/java

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

Guava Cache 集成

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

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

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

在 Spring Boot 中集成 Guava Cache 很是容易,只须要在 pom.xml 中增长Guava 依赖便可。springboot

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>复制代码

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

若是想对Guava Cache 更深刻的了解,能够参考 ifeve.com/google-guav…并发

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

Bean 'cacheManager' of type [class org.springframework.cache.guava.GuavaCacheManager]复制代码

个性化配置

若是想自定义参数,例如存活时间,缓存最大数目等。咱们能够经过 Java Config 的方式,进行配置。

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

@Configuration
@EnableCaching
public class GuavaCacheConfig { 
    @Bean
    public CacheManager cacheManager() {
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheBuilder(
            CacheBuilder.newBuilder().
            expireAfterWrite(10, TimeUnit.SECONDS).
            maximumSize(1000));
        return cacheManager;
    }
}复制代码

源代码

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

(完)

更多精彩文章,尽在「服务端思惟」微信公众号!

相关文章
相关标签/搜索