maven配置
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
配置文件
spring:
cache:
type: caffeine
缓存配置类
@Slf4j
@Configuration
@EnableCaching
@EnableCaffeineHttpSession(maxInactiveIntervalInSeconds = 18000)
public class CacheConfig {
private static final long MAX_INACTIVE_INTERVAL = 300 * 60 * 1000 * 1000L;
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
// 配置缓存及其过期时间
cacheManager.setCaffeine(Caffeine.newBuilder()
.expireAfter(new Expiry<>() {
@Override
public long expireAfterCreate(Object key, Object value, long currentTime) {
return getMaxInterval(key);
}
@Override
public long expireAfterUpdate(Object key, Object value, long currentTime, @NonNegative long currentDuration) {
return getMaxInterval(key);
}
@Override
public long expireAfterRead(Object key, Object value, long currentTime, @NonNegative long currentDuration) {
return currentDuration;
}
private long getMaxInterval(Object key) {
String[] keyStrs = key.toString().split("#");
return keyStrs.length > 1 ? Long.valueOf(keyStrs[1]) * 1000L : MAX_INACTIVE_INTERVAL;
}
})
.initialCapacity(100)
.maximumSize(10_000));
return cacheManager;
}
}
时间单位是纳秒,所以 1s=1*1000*1000
使用,无自定义时间
@Cacheable(value = "recommend_articles", key = "#siteId.toString().concat('-').concat(#count.toString())")
@Override
public List<Article> listRecommendOrHotArticle(Long siteId, Integer count) {
return baseMapper.listRecommendOrHotArticle(siteId, count);
}
自定义时间(30s)
@Cacheable(value = "recommend_articles#30000", key = "#siteId.toString().concat('-').concat(#count.toString())")
@Override
public List<Article> listRecommendOrHotArticle(Long siteId, Integer count) {
return baseMapper.listRecommendOrHotArticle(siteId, count);
}