springboot caffeine缓存配置

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);
    }
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值