Simple example of LoadingCache, use googleCacheCache to cache the first data in the database every day and save it

Keith
Apr 21, 2022

--

Use LoadingCache to cache the first data in the database every day and save it

private LoadingCache<String, Integer> minId = CacheBuilder.newBuilder().expireAfterWrite(1L, TimeUnit.DAYS).build(new CacheLoader<String, Integer>() {
@Override
public Integer load(String mixdate) throws Exception {
Date date = LocalDate.parse(StringUtils.substringAfter(s, "@")).toDate();
// 在本地没有缓存的时候会调用该方法进行加载,将获取的值进行缓存并返回结果
if (ACTIVE_COUNTER.startsWith(mixdate)) {
LoginLog loginLog = loginLogRepository.getTopByLoginTimeBeforeOrderByIdDesc(date);
if (loginLog != null) {
return loginLog.getId();
}
} else if (PLAYED_COUNTER.startsWith(mixdate)) {
ViewHistory viewHistory = viewHistoryRepository.getTopByViewtimeBeforeOrderByIdDesc(date);
if (viewHistory != null) {
return viewHistory.getId();
}
} else if (ADCLICK_COUNTER.startsWith(mixdate)) {
AdvClickHistory advClickHistory = advClickHistoryRepository.getTopByCreateTimeBeforeOrderByIdDesc(date);
if (advClickHistory != null) {
return advClickHistory.getId();
}
}
return 0;
}
});
minId.getUnchecked(StringUtils.join(type, "@", date));

Take out the data key of the day here, because the date is different every day, so the first data of the day will be obtained and cached!

--

--