springboot结合caffenine缓存

一、引入依赖

由于使用jdk9.0更新的caffenine版本不支持,这里使用低版本caffenine

 		<dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.8</version> //低版本
        </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

二、CaffenineConfig配置文件

这里配置了名字为pic的缓存
具体其他参数自己按照业务修改

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;



@Configuration
@EnableCaching
public class CaffeineConfig {

    private static final Logger logger = LoggerFactory.getLogger(CaffeineConfig.class);

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();

        cacheManager.registerCustomCache("pic", Caffeine.newBuilder()
                .expireAfterWrite(5,TimeUnit.MINUTES)
                .maximumSize(100000)
                .removalListener((key, value, cause) ->
                        logger.info("Key {} removed due to {}", key, cause))
                .build()
        );
        return cacheManager;
    }
}

三、在service使用

1.注意依赖(实战中不小心使用原配置中swagger的注解导致失败)

import org.springframework.cache.annotation.Cacheable;

在查询方法上面添加注解
工具查看是否命中缓存
全局初始化

 private final CacheManager cacheManager;
public boolean isCacheHit(int n) {
        Cache cache = cacheManager.getCache("pic");
        if (cache != null) {
            Cache.ValueWrapper valueWrapper = cache.get(n);
            return valueWrapper != null;
        }
        return false;
    }

四、controller调用查看是否命中缓存

在mes中会返回是否命中
在这里插入图片描述

第一次查询

在这里插入图片描述

第二次查询

在这里插入图片描述

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值