简介
Caffeine is a high performance, near optimal caching library. For more details, see our user's guide and browse the API docs for the latest release.
Caffeine是一个基于java的缓存库,本文简单介绍它如何在SpringBoot中集成并使用。
引入依赖
<!--===============缓存================-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.7.0</version>
</dependency>
使用
Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache
这里使用LoadingCache接口去做缓存。
// 帖子列表缓存
private LoadingCache<String, List<Post>> postListCache;
// 帖子总数缓存
private LoadingCache<Integer, Integer> postRowsCache;
使用了@PostConstruct注解去初始化缓存构建逻辑,这样就会在程序启动后自动构建缓存逻辑(并不会马上执行)
@PostConstruct
public void init() {
// 初始化热门帖子列表缓存
postListCache = Caffeine.newBuilder()
.maximumSize(maxSize)
//设置过期时间
.expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
.build(new CacheLoader<String, List<Post>>() {
@Nullable
@Override
public List<Post> load(@NonNull String key) throws Exception {
if (key == null || key.length() == 0) {
throw new IllegalArgumentException("参数错误!");
}
int offset = Integer.valueOf(key);
logger.info("load post list from DB.");
return postDao.listByHot(offset);
}
});
// 初始化帖子总数缓存
postRowsCache = Caffeine.newBuilder()
.maximumSize(maxSize)
.expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
.build(new CacheLoader<Integer, Integer>() {
@Nullable
@Override
public Integer load(@NonNull Integer key) throws Exception {
logger.info("load post rows from DB.");
return postDao.count();
}
});
}
获取缓存
posts = postListCache.get(offset+"");
total = postRowsCache.get(0);