在现代应用开发中,缓存是提升系统性能的核心技术之一。Spring Cache作为Spring生态的缓存抽象层,提供统一的缓存操作接口。本文将通过完整示例演示SpringBoot项目如何整合Spring Cache。
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-cacheartifactId>
dependency>
<dependency>
<groupId>com.github.ben-manes.caffeinegroupId>
<artifactId>caffeineartifactId>
dependency>
dependencies>
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500, expireAfterWrite=10m
如果是使用redis做缓存的话,这一步可不做配置,然后如果缓存的是对象则需要实现Serializable
@Service
public class ProductService {
// 缓存结果
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
// 模拟数据库查询
return findProductInDB(id);
}
// 更新缓存
@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
return saveProductToDB(product);
}
// 删除缓存
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
deleteProductInDB(id);
}
}
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(500)
.expireAfterWrite(10, TimeUnit.MINUTES));
return cacheManager;
}
}
@Cacheable(value = "products",
key = "#id",
condition = "#id < 1000",
unless = "#result.stock < 10")
public Product getSpecialProduct(Long id) { /*...*/ }
实现方案 | 适用场景 | 特点 |
---|---|---|
Caffeine | 本地缓存 | 高性能,内存管理优秀 |
Redis | 分布式缓存 | 数据共享,持久化支持 |
Ehcache | 复杂本地缓存 | 支持磁盘持久化 |
通过Spring Cache的抽象层,我们可以:
✅ 快速集成多种缓存实现
✅ 通过声明式注解管理缓存
✅ 灵活配置缓存策略
✅ 轻松切换缓存方案