Spring Boot 集成 Caffeine 本地缓存配置与应用实践
Caffeine 是一款基于 Java 的高性能本地缓存库,其底层采用了 W-TinyLFU 淘汰算法,在读写性能和命中率上表现优异。在 Spring Boot 项目中,可以通过 Spring Cache 抽象层无缝接入 Caffeine。以下是具体的集成与使用方案。
引入核心依赖
要在项目中使用 Caffeine,需要同时引入 Spring 的缓存启动器以及 Caffeine 库本身。在 Maven 项目的 pom.xml 中添加以下依赖:
<dependencies>
<!-- 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>
</dependencies>
定义缓存配置
接下来需要开启缓存支持,并实例化 Caffeine 构建器与缓存管理器。在这里我们可以自定义缓存的初始容量、最大条目数以及过期策略。
@Configuration
@EnableCaching
public class LocalCacheConfiguration {
@Bean
public Caffeine<Object, Object> caffeineSpec() {
return Caffeine.newBuilder()
.initialCapacity(128)
.maximumSize(1024)
.expireAfterAccess(30, TimeUnit.MINUTES)
.recordStats();
}
@Bean
public CacheManager localCacheManager(Caffeine<Object, Object> caffeineSpec) {
CaffeineCacheManager manager = new CaffeineCacheManager("product_info_cache");
manager.setCaffeine(caffeineSpec);
return manager;
}
}
构建业务服务层
创建一个模拟的数据模型和业务服务类。通过 @Cacheable 注解,Spring 会在方法执行前检查缓存,若命中则直接返回,否则执行方法并将结果写入缓存。
@Data
@AllArgsConstructor
public class ProductInfo {
private Long id;
private String name;
private Double price;
}
@Service
@Slf4j
public class ProductQueryService {
private static final Map<Long, ProductInfo> MOCK_DB = new ConcurrentHashMap<>();
static {
MOCK_DB.put(101L, new ProductInfo(101L, "Mechanical Keyboard", 299.99));
MOCK_DB.put(102L, new ProductInfo(102L, "Wireless Mouse", 99.50));
MOCK_DB.put(103L, new ProductInfo(103L, "4K Monitor", 450.00));
}
@Cacheable(cacheNames = "product_info_cache", key = "#productId")
public ProductInfo getProductById(Long productId) {
log.info("Fetching product from database, ID: {}", productId);
return MOCK_DB.get(productId);
}
}
控制器与缓存手动操作
在 Web 层,除了通过服务层自动触发缓存外,有时我们需要直接通过 CacheManager 手动读取或操作缓存数据。以下控制器展示了常规接口调用与手动检查缓存状态的实现。
@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductApiController {
private final ProductQueryService productQueryService;
private final CacheManager cacheManager;
@GetMapping("/{id}")
public ProductInfo fetchProduct(@PathVariable Long id) {
return productQueryService.getProductById(id);
}
@GetMapping("/cache-inspect/{id}")
public ProductInfo inspectCachedProduct(@PathVariable Long id) {
Cache cache = cacheManager.getCache("product_info_cache");
if (cache != null) {
Cache.ValueWrapper wrapper = cache.get(id);
return wrapper != null ? (ProductInfo) wrapper.get() : null;
}
return null;
}
}
通过上述配置与代码,应用在处理重复的商品查询请求时,将直接从 Caffeine 内存中获取数据,从而显著降低数据库 I/O 压力并提升接口响应速度。手动获取缓存的机制也为复杂的缓存失效或数据预热场景提供了灵活的底层操作能力。