欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > Spring Boot 3.4.3 基于 Caffeine 实现本地缓存

Spring Boot 3.4.3 基于 Caffeine 实现本地缓存

2025/4/2 11:21:47 来源:https://blog.csdn.net/lssffy/article/details/146765927  浏览:    关键词:Spring Boot 3.4.3 基于 Caffeine 实现本地缓存

在现代企业级应用中,缓存是提升系统性能和响应速度的关键技术。通过减少数据库查询或复杂计算的频率,缓存可以显著优化用户体验。Spring Boot 3.4.3 提供了强大的缓存抽象支持,而 Caffeine 作为一款高性能的本地缓存库,因其优异的吞吐量和灵活的配置,成为许多开发者的首选。本文将详细介绍如何在 Spring Boot 3.4.3 中集成 Caffeine 实现本地缓存功能,并提供完整的代码示例,助你在2025年的开发实践中快速落地高效缓存方案。


1. Caffeine 简介
1.1 什么是 Caffeine?

Caffeine 是一个基于 Java 的高性能本地缓存库,旨在替代传统的 Guava Cache。它采用了 Window TinyLFU(W-TinyLFU)淘汰算法,提供更高的命中率和更低的内存占用。Caffeine 支持丰富的配置选项,如过期策略、容量限制和异步加载,广泛应用于需要快速响应的场景。

1.2 Caffeine 的优点
  • 高性能:优于 Guava Cache 和 ConcurrentHashMap 的吞吐量。
  • 灵活性:支持按时间、大小和引用淘汰数据。
  • Spring 集成:与 Spring Cache 无缝衔接,注解驱动开发。
  • 轻量级:无需外部服务,适用于本地缓存需求。
1.3 适用场景
  • 频繁查询的静态数据(如配置信息)。
  • 计算代价高昂的结果缓存(如复杂算法)。
  • 高并发场景下的热点数据存储。

2. 项目实战

以下是基于 Spring Boot 3.4.3 和 Caffeine 实现本地缓存的完整步骤。

2.1 添加 Maven 依赖

pom.xml 中添加必要的依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.4.3</version></parent><artifactId>springboot-caffeine</artifactId><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!-- Spring Boot Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 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><version>3.1.8</version></dependency></dependencies>
</project>

说明:

  • spring-boot-starter-cache:提供 Spring Cache 抽象支持。
  • caffeine:核心缓存库,版本 3.1.8 是当前稳定版。
2.2 配置 Caffeine 缓存

创建一个配置类,定义 Caffeine 的缓存属性:

package cn.joyous.config;import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.concurrent.TimeUnit;@Configuration
public class CacheConfig {@Beanpublic CacheManager cacheManager() {CaffeineCacheManager cacheManager = new CaffeineCacheManager();cacheManager.setCaffeine(Caffeine.newBuilder().initialCapacity(100)           // 初始容量.maximumSize(1000)             // 最大条目数.expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期.recordStats());               // 记录缓存统计信息return cacheManager;}
}

代码说明:

  • initialCapacity:初始化缓存容量。
  • maximumSize:限制最大缓存条目,超出时按 W-TinyLFU 淘汰。
  • expireAfterWrite:设置过期时间。
  • recordStats:启用统计,可用于监控命中率。
2.3 创建服务层

定义一个服务类,使用缓存注解:

package cn.joyous.service;import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;@Service
public class UserService {@Cacheable(value = "users", key = "#id")public String getUserById(Long id) {// 模拟数据库查询System.out.println("从数据库查询用户: " + id);return "User-" + id;}@CacheEvict(value = "users", key = "#id")public void deleteUser(Long id) {// 模拟删除操作System.out.println("删除用户: " + id);}
}

注解说明:

  • @Cacheable:查询时优先从缓存获取,若无则执行方法并缓存结果。
  • @CacheEvict:删除时清理指定缓存。
  • value:缓存名称,key:缓存键。
2.4 创建控制器

创建一个 RESTful 接口调用服务:

package cn.joyous.controller;import cn.itbeien.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/user/{id}")public String getUser(@PathVariable Long id) {return userService.getUserById(id);}@DeleteMapping("/user/{id}")public String deleteUser(@PathVariable Long id) {userService.deleteUser(id);return "User " + id + " deleted";}
}
2.5 启用缓存

在启动类上添加 @EnableCaching

package cn.joyous;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication
@EnableCaching
public class CaffeineApplication {public static void main(String[] args) {SpringApplication.run(CaffeineApplication.class, args);}
}
2.6 测试缓存功能
  1. 启动应用。
  2. 访问 http://localhost:8080/api/user/1,控制台输出“从数据库查询用户: 1”。
  3. 再次访问相同 URL,无控制台输出,说明命中缓存。
  4. 调用 DELETE http://localhost:8080/api/user/1,缓存被清除,下次查询重新加载。

3. 进阶功能(可选)
  1. 多级缓存配置
    支持不同缓存策略:

    @Bean
    public CacheManager cacheManager() {CaffeineCacheManager cacheManager = new CaffeineCacheManager("users", "configs");cacheManager.setCaffeineCache("users", Caffeine.newBuilder().maximumSize(1000).expireAfterWrite(10, TimeUnit.MINUTES).build());cacheManager.setCaffeineCache("configs", Caffeine.newBuilder().maximumSize(500).expireAfterAccess(1, TimeUnit.HOURS).build());return cacheManager;
    }
    
  2. 异步加载
    支持异步缓存填充:

    @Bean
    public CacheManager cacheManager() {CaffeineCacheManager cacheManager = new CaffeineCacheManager();cacheManager.setCaffeine(Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(1000));cacheManager.setAsyncCache(true);return cacheManager;
    }
    
  3. 缓存统计
    查看命中率:

    @Autowired
    private CacheManager cacheManager;public void printStats() {CaffeineCache cache = (CaffeineCache) cacheManager.getCache("users");System.out.println(cache.getNativeCache().stats());
    }
    

4. 总结

Spring Boot 3.4.3 结合 Caffeine 提供了一种高效的本地缓存实现方案。通过简单的配置和注解,你可以在项目中快速集成缓存功能,提升性能并减少数据库压力。Caffeine 的高性能和灵活性使其成为替代传统缓存工具的理想选择。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词