Springboot集成Caffeine

前言:

在系统中,有些数据,访问十分频繁,往往把这些数据放入分布式缓存中,但为了减少网络传输,加快响应速度,缓存分布式缓存读压力,会把这些数据缓存到本地JVM中,大多是先取本地缓存中,再取分布式缓存中的数据,Caffeine是一个高性能Java 缓存库,使用Java8对Guava缓存重写版本,在Spring Boot 2.0中将取代Guava

一、引入依赖

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

二、开启缓存

主启动类添加注解@EnableCaching

三、Controller层

@RestController
public class CacheController {
    @Autowired
    CacheService cacheService;

    @RequestMapping("cacheMethod01")
    public String cacheMethod01(String key) {
        return cacheService.cacheMethod01(key);
    }

    @RequestMapping("cacheMethod02")
    public String cacheMethod02(String key) {
        return cacheService.cacheMethod02(key);
    }

}

四、Service层

@Service
public class CacheService {
    @Cacheable(value = "cacheMethod01", key = "#key")
    public String cacheMethod01(String key) {
        System.out.println("cacheMethod01()方法执行,key="+key);
        return "cacheMethod01...,key="+key;
    }
    @Cacheable(value = "cacheMethod02", key = "#key")
    public String cacheMethod02(String key) {
        System.out.println("cacheMethod02()方法执行,key="+key);
        return "cacheMethod02...,key="+key;
    }

}

五、消亡时间枚举类

public enum CacheType {

    cacheMethod01(10),

    cacheMethod02(5);

    private int expires; // 消亡时间

    CacheType(int expires) {
        this.expires = expires;
    }

    public int getExpires() {
        return expires;
    }
}

六、配置类

@Configuration
public class CaffeineConfig {

    @Bean
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<CaffeineCache> caffeineCaches = new ArrayList<>();

        for (CacheType cacheType : CacheType.values()) {
            caffeineCaches.add(new CaffeineCache(cacheType.name(),
                    Caffeine.newBuilder()
                            .expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS)
                            .build()));
        }

        cacheManager.setCaches(caffeineCaches);

        return cacheManager;
    }
}

七、配置文件(不推荐)

spring.cache.cache-names=cacheMethod01, cacheMethod02
spring.cache.caffeine.spec=initialCapacity=50,maximumSize=500,expireAfterWrite=5s
spring.cache.type=caffeine
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值