Loading...
Loading...
使用 Spring Cache 抽象实现缓存策略,支持多种缓存提供商(Redis、Caffeine、EhCache 等)。使用场景:(1) 减少数据库查询,(2) 提高 API 响应时间,(3) 实现读写缓存策略,(4) 配置缓存失效策略,(5) 实现多级缓存
npx skill4agent add lambert0529/skills java-cachespring-boot-starter-cache@EnableCaching@Cacheable@CachePut@CacheEvict<!-- Spring Cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Redis 缓存提供商 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Caffeine 本地缓存(可选) -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeKeysWith(
RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.withCacheConfiguration("products",
config.entryTtl(Duration.ofHours(1)))
.withCacheConfiguration("users",
config.entryTtl(Duration.ofMinutes(30)))
.build();
}
}@Service
@RequiredArgsConstructor
public class ProductService {
private final ProductRepository productRepository;
@Cacheable(value = "products", key = "#id")
public Product findById(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
}
@CachePut(value = "products", key = "#result.id")
public Product update(Long id, UpdateProductRequest request) {
Product product = findById(id);
product.update(request);
return productRepository.save(product);
}
@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
productRepository.deleteById(id);
}
@CacheEvict(value = "products", allEntries = true)
public void clearCache() {
// 清除所有缓存
}
}@Cacheable(
value = "users",
key = "#email",
condition = "#email != null",
unless = "#result == null"
)
public User findByEmail(String email) {
return userRepository.findByEmail(email).orElse(null);
}@Cacheable(value = {"l1Cache", "l2Cache"}, key = "#id")
public Product findById(Long id) {
// 先查 L1(本地缓存),再查 L2(Redis),最后查数据库
return productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
}"product:123""123"@PostConstructApplicationRunnerassets/