Spring Boot 整合 Caffeine 缓存教程

精心整理了最新的面试资料和简历模板,有需要的可以自行获取

点击前往百度网盘获取
点击前往夸克网盘获取


Spring Boot 整合 Caffeine 缓存教程

Caffeine 是一个高性能的 Java 缓存库,与 Spring Boot 结合使用可以显著提升应用性能。以下是整合步骤:


一、环境准备

  1. 使用 Spring Boot 2.x 或更高版本
  2. 开发工具:IDEA/Eclipse + Maven/Gradle

二、添加依赖

pom.xml 中添加依赖:

<!-- Spring Boot Cache Starter -->
<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>
    <version>3.1.8</version> <!-- 检查最新版本 -->
</dependency>

三、启用缓存功能

在启动类添加 @EnableCaching 注解:

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

四、配置 Caffeine 缓存

application.yml 中配置:

spring:
  cache:
    cache-names: userCache,productCache
    caffeine:
      spec: maximumSize=500,expireAfterWrite=10m

或通过 @Bean 配置:

@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .initialCapacity(100)
                .maximumSize(500)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .weakKeys()
                .recordStats());
        return cacheManager;
    }
}

五、使用缓存注解

1. @Cacheable 示例

@Service
public class UserService {

    // 结果缓存到 userCache,key 为 userId
    @Cacheable(value = "userCache", key = "#userId")
    public User getUserById(Long userId) {
        // 模拟数据库查询
        return userRepository.findById(userId).orElse(null);
    }
}

2. @CacheEvict 示例

@CacheEvict(value = "userCache", key = "#userId")
public void deleteUser(Long userId) {
    userRepository.deleteById(userId);
}

3. @CachePut 示例

@CachePut(value = "userCache", key = "#user.id")
public User updateUser(User user) {
    return userRepository.save(user);
}

六、高级配置参数

参数配置说明
maximumSize最大缓存条目数
expireAfterWrite写入后固定时间过期
expireAfterAccess最后一次访问后过期
refreshAfterWrite写入后定时刷新(需配合 CacheLoader)
weakKeys/weakValues使用弱引用键/值
recordStats开启统计功能

七、查看缓存统计

@Autowired
private CacheManager cacheManager;

public void printCacheStats() {
    CaffeineCache caffeineCache = (CaffeineCache) cacheManager.getCache("userCache");
    com.github.benmanes.caffeine.cache.Cache<Object, Object> nativeCache = 
        caffeineCache.getNativeCache();
    
    CacheStats stats = nativeCache.stats();
    System.out.println("命中率: " + stats.hitRate());
    System.out.println("加载次数: " + stats.loadCount());
}

八、注意事项

  1. 缓存穿透:对 null 值进行缓存(使用 @Cacheable(unless = "#result == null")
  2. 缓存雪崩:设置不同的过期时间
  3. 重要数据建议配合持久化存储使用
  4. 生产环境建议配置缓存监控

通过以上步骤,您已经成功将 Caffeine 缓存集成到 Spring Boot 应用中。可通过调整配置参数优化缓存策略,建议结合具体业务场景进行性能测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘵奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值