Springboot中整合caffeine缓存

本文介绍如何在Spring Boot项目中配置和使用Caffeine缓存,包括依赖引入、YAML配置、自定义配置类及注解使用,提供灵活的缓存策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring-boot中配置和使用Caffeine Cache

第一步:引入依赖
这里不知道为什么很多版本的依赖包用不了,用不了的话你剋实施其他的

 <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.5.5</version>
        </dependency>

第二部:配置相关文档:
有两种方法:

1.application.yml配置文件中配置:
优点:简单
缺点:无法针对每个cache配置不同的参数,比如过期时长、最大容量

2.配置类中配置
优点:可以针对每个cache配置不同的参数,比如过期时长、最大容量
缺点:要写一点代码

  1. 在yml文件中
spring:
  cache:
    type: caffeine
    cache-names:
    - getPersonById
    - name2
    caffeine:
      spec: maximumSize=500,expireAfterWrite=5s
  1. 在启动类中加入@EnableCaching
  2. 在对应类中加入对应的缓存方法:
@CacheConfig(cacheNames = "emp")
@Service
public class EmployService {

    @Autowired
    EmploeeMapper emploeeMapper;

    @Cacheable(cacheNames = {"emp"})
    public Employee getEmpById(Integer id){
        System.out.println("查询" + id + "号员工");
        Employee employee = emploeeMapper.getEmpById(id);
        System.out.print(employee);
        return  employee;
    }
}

运行后:可以在debug控制台中看到CaffeineCacheConfig被引用了

第二种用配置文件配置,这种方法更加灵活:

package com.xjj.config;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.github.benmanes.caffeine.cache.Caffeine;

/**
 * Cache配置類,用于缓存数据
 * @author XuJijun
 *
 */
@Configuration
@EnableCaching
public class CacheConfig {

    public static final int DEFAULT_MAXSIZE = 50000;
    public static final int DEFAULT_TTL = 10;

    /**
     * 定義cache名稱、超時時長(秒)、最大容量
     * 每个cache缺省:10秒超时、最多缓存50000条数据,需要修改可以在                构造方法的参数中指定。
     */
    public enum Caches{
        getPersonById(5), //有效期5秒
        getSomething, //缺省10秒
        getOtherthing(300, 1000), //5分钟,最大容量1000
        ;

        Caches() {
        }

        Caches(int ttl) {
            this.ttl = ttl;
        }

        Caches(int ttl, int maxSize) {
            this.ttl = ttl;
            this.maxSize = maxSize;
        }

        private int maxSize=DEFAULT_MAXSIZE;    //最大數量
        private int ttl=DEFAULT_TTL;        //过期时间(秒)

        public int getMaxSize() {
            return maxSize;
        }
        public int getTtl() {
            return ttl;
        }
    }

    /**
     * 创建基于Caffeine的Cache Manager
     * @return
     */
    @Bean
    @Primary
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        ArrayList<CaffeineCache> caches = new ArrayList<CaffeineCache>();
        for(Caches c : Caches.values()){
            caches.add(new CaffeineCache(c.name(), 
                Caffeine.newBuilder().recordStats()
                .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
                .maximumSize(c.getMaxSize())
                .build())
            );
        }

        cacheManager.setCaches(caches);

        return cacheManager;
    }

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值