You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中启动时从DB加载数据到Caffeine缓存并复用缓存数据

Spring Boot 启动时加载数据到Caffeine缓存并复用的完整实现方案

我来给你梳理一个完整的落地方案,从依赖准备、缓存配置,到启动加载数据、业务中复用缓存的全流程都讲清楚,直接就能套用到你的项目里。

第一步:添加必要依赖

首先得确保项目引入Spring Cache和Caffeine的核心依赖,如果你用Maven,就在pom.xml里加入这些:

<!-- Spring Cache 核心依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Caffeine 缓存实现依赖 -->
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>
<!-- 数据库访问依赖(以Spring Data JPA为例,根据你的实际访问方式调整) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

如果是Gradle项目,对应依赖配置如下:

implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'com.github.ben-manes.caffeine:caffeine'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

第二步:完善Caffeine缓存配置类

你给出的基础配置可以再优化,比如增加过期策略(可选),确保缓存名称和后续业务逻辑一致。调整后的完整配置如下:

import org.springframework.cache.CacheManager;
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;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

    @Bean(name = "cacheManager")
    @Primary
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        // 配置缓存:名称为Cache_Data,最大容量400,访问后30分钟过期(可根据业务调整)
        CaffeineCache dataCache = new CaffeineCache(
                "Cache_Data",
                Caffeine.newBuilder()
                        .maximumSize(400)
                        .expireAfterAccess(30, TimeUnit.MINUTES)
                        .build()
        );
        cacheManager.setCaches(Arrays.asList(dataCache));
        return cacheManager;
    }
}

关键配置说明:

  • maximumSize(400):缓存最多存储400条数据,超出后自动淘汰最少使用的条目
  • expireAfterAccess:缓存条目30分钟未被访问则自动过期,也可换成expireAfterWrite实现写入后固定时间过期

第三步:数据库实体与数据访问层

假设你要加载的是DataEntity数据,先定义实体类对应数据库表:

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "data_table") // 替换为你的实际数据库表名
public class DataEntity {
    @Id
    private Long id;
    private String content;
    // 省略getter、setter、toString方法
}

再定义数据访问Repository(以Spring Data JPA为例):

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface DataRepository extends JpaRepository<DataEntity, Long> {
    // 自定义查询方法,这里用全量查询示例
    List<DataEntity> findAll();
}

第四步:业务服务层实现(缓存复用+启动加载)

核心是实现缓存复用逻辑,同时在项目启动时主动将数据加载到缓存。推荐用ApplicationRunner实现启动加载,它会在Spring容器完全启动后执行,能更好处理依赖顺序问题。

1. 业务服务类(缓存逻辑)

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@CacheConfig(cacheManager = "cacheManager", cacheNames = "Cache_Data")
public class DataService {

    private final DataRepository dataRepository;

    // 构造注入
    public DataService(DataRepository dataRepository) {
        this.dataRepository = dataRepository;
    }

    // 从缓存获取数据,缓存未命中时查询数据库并写入缓存
    @Cacheable(key = "'allData'") // 用固定key标识全量数据,方便后续复用
    public List<DataEntity> getAllData() {
        System.out.println("从数据库查询数据..."); // 测试用,实际可删除
        return dataRepository.findAll();
    }

    // 可选:手动刷新缓存方法
    // @CachePut(key = "'allData'")
    // public List<DataEntity> refreshData() {
    //     return dataRepository.findAll();
    // }
}

2. 启动加载组件

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class CacheLoaderRunner implements ApplicationRunner {

    private final DataService dataService;

    public CacheLoaderRunner(DataService dataService) {
        this.dataService = dataService;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 项目启动时调用查询方法,触发缓存写入
        System.out.println("启动时加载数据到缓存...");
        dataService.getAllData();
    }
}

第五步:启用Spring Cache

最后在Spring Boot启动类上添加@EnableCaching注解,开启缓存功能:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

验证效果

启动项目后,控制台会输出启动时加载数据到缓存...和从数据库查询数据...,说明数据已从数据库加载到缓存。后续再调用getAllData方法时,不会再输出数据库查询日志,而是直接从缓存获取数据。

内容的提问来源于stack exchange,提问作者ulagan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:17:46