Spring Boot 集成 Caffeine 缓存

Spring Boot 集成 Caffeine 缓存

Caffeine 是个高性能的开源 Java 内存缓存库,具有较高的命中率和出色的并发能力。在 Spring Boot 中集成也非常简单,提供了各种开箱既用的工具。

集成 Caffeine

Spring Boot 对其它组件的集成非常简单,按照约定大于配置的原则,不做特殊配置的时候完全不需要甚至不写配置就可以使用,因为大多数开源框架基本都会提供 starter 包,提供了对最常见的默认配置。

先引入 Spring Boot 的缓存支持 starter

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Spring 的 Cache 提供了非常好用的工具,让使用到缓存的代码不需要关心缓存的实现,在后期更换实现后不需要对原有的代码作任何变更。这样在初期业务量不大的情况下可以先上一级的内存缓存,在后期可以修改实现增加 Redis 作二级缓存。

Spring Boot Cache 中会自动配置,如果引入了 Caffeine 的包, spring-boot-starter-cache 会自动配置 CaffeineCacheManager,可以通过以下配置对缓存进行配置。

1
2
spring.cache.cache-names=cache1,cache2
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

cache-names 定义了缓存的名字,spec 定义了缓存大小鬼失效时间。这种配置简单虽简单,但是灵活性不够,不能同时配置多种不同的缓存策略。

引入 Caffeine 的包

1
2
3
4
5
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>${caffeine.version}</version>
</dependency>

编写 Configuration 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Configuration
@EnableCaching
public class CaffeineConfiguration {
@Bean
public CacheManager caffeineCacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();

List<CaffeineCache> caffeineCaches = new ArrayList<>();

for (CacheConstant.CacheType cacheType : CacheConstant.CacheType.values()) {
caffeineCaches.add(new CaffeineCache(cacheType.toString(),
Caffeine.newBuilder()
.expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS)
.maximumSize(cacheType.getMaxSize())
.build()));
}

cacheManager.setCaches(caffeineCaches);

return cacheManager;
}
}

上面代码中,通过 CacheType 枚举构造了几种不同缓存策略的缓存,在应用中直接使用 Cache Name 既可将数据直接缓存。

使用

必须要在 Configuration 类中使用 @EnableCaching 才能启用缓存。

1
2
3
4
@Cacheable(value = CacheConstant.DEFAULT_CACHING, key = "#userId + '_info'")
public User getUserByUserId(String userId) {
return userMapper.selectOne(userId);
}

Spring Cache 注解的使用可以参考我翻译的相关文章。

作者

Jakes Lee

发布于

2018-05-06

更新于

2021-11-18

许可协议

评论