精心整理了最新的面试资料和简历模板,有需要的可以自行获取
Spring Boot 整合 Caffeine 缓存教程
Caffeine 是一个高性能的 Java 缓存库,与 Spring Boot 结合使用可以显著提升应用性能。以下是整合步骤:
一、环境准备
- 使用 Spring Boot 2.x 或更高版本
- 开发工具: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());
}
八、注意事项
- 缓存穿透:对 null 值进行缓存(使用
@Cacheable(unless = "#result == null")
) - 缓存雪崩:设置不同的过期时间
- 重要数据建议配合持久化存储使用
- 生产环境建议配置缓存监控
通过以上步骤,您已经成功将 Caffeine 缓存集成到 Spring Boot 应用中。可通过调整配置参数优化缓存策略,建议结合具体业务场景进行性能测试。