Spring Cache的详细使用

Spring Cache 详解及应用场景

Spring Cache 是 Spring 框架提供的缓存抽象层,它通过注解的方式简化缓存的使用,允许开发者在不修改业务逻辑的情况下,轻松地为方法添加缓存功能。它支持多种缓存实现(如 Redis、Ehcache、Caffeine 等),并提供统一的 API 进行管理。


1. Spring Cache 的核心概念

Spring Cache 主要基于 AOP(面向切面编程) 实现,其核心接口和注解包括:

1.1 核心接口

  • Cache:定义缓存的基本操作(如 getputevict 等)。
  • CacheManager:管理多个 Cache 实例,如 RedisCacheManagerEhCacheManager
  • KeyGenerator:用于生成缓存的 Key(默认使用方法的参数组合)。

1.2 核心注解

注解作用示例
@Cacheable方法结果缓存,如果缓存存在则直接返回@Cacheable("users")
@CachePut强制更新缓存(通常用于更新操作)@CachePut(value="users", key="#user.id")
@CacheEvict删除缓存(用于删除或更新后清理缓存)@CacheEvict(value="users", key="#id")
@Caching组合多个缓存操作@Caching(evict={@CacheEvict("users"), @CacheEvict("orders")})
@CacheConfig类级别的缓存公共配置@CacheConfig(cacheNames="users")

2. Spring Cache 的应用场景

Spring Cache 适用于 读多写少、计算耗时、数据变化不频繁 的场景,例如:

2.1 数据库查询缓存

场景:频繁查询数据库,但数据变化较少(如商品信息、用户信息)。

@Service
public class UserService {
    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null); // 仅第一次查数据库,后续走缓存
    }
}

2.2 接口响应缓存

场景:高并发接口(如首页数据、排行榜),减少计算或数据库压力。

@RestController
public class ProductController {
    @GetMapping("/products")
    @Cacheable("products")
    public List<Product> getProducts() {
        return productService.findAll(); // 缓存接口返回结果
    }
}

2.3 方法结果缓存(计算密集型)

场景:复杂计算(如数据分析、报表生成),缓存计算结果。

@Service
public class ReportService {
    @Cacheable(value = "reports", key = "#year + '-' + #month")
    public Report generateMonthlyReport(int year, int month) {
        // 模拟耗时计算
        return calculateReport(year, month);
    }
}

2.4 缓存更新与失效

场景:数据变更时同步更新或删除缓存(如用户信息修改)。

@Service
public class UserService {
    @CachePut(value = "users", key = "#user.id") // 更新缓存
    public User updateUser(User user) {
        return userRepository.save(user);
    }

    @CacheEvict(value = "users", key = "#id") // 删除缓存
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

3. Spring Cache 的缓存实现

Spring Cache 本身是抽象的,需要结合具体的缓存技术使用,常见的有:

缓存实现适用场景特点
Caffeine本地缓存(高性能)基于内存,适合单机应用
Redis分布式缓存支持集群,适合微服务
Ehcache本地/分布式缓存支持磁盘持久化
Guava Cache本地缓存(旧版)已被 Caffeine 取代

配置示例(Redis + Spring Cache)

# application.yml
spring:
  cache:
    type: redis
  redis:
    host: localhost
    port: 6379
@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
        return RedisCacheManager.builder(factory).build();
    }
}

4. 最佳实践 & 注意事项

合理设置缓存Key:避免冲突(如 key="#user.id")。
设置缓存过期时间:防止数据不一致(如 @Cacheable(value="users", key="#id", ttl=300))。
避免缓存大对象:如 List 全部数据,可考虑分页缓存。
注意缓存穿透:对 null 值进行缓存(如 @Cacheable(unless="#result == null"))。
避免缓存雪崩:设置随机 TTL(如 Redisexpire 时间加随机值)。


总结

Spring Cache 提供了一种 无侵入式 的缓存方案,适用于:

  • 高频查询(减少数据库压力)
  • 复杂计算(缓存计算结果)
  • 接口优化(提升响应速度)

结合 Redis、Caffeine 等缓存技术,可以灵活应对 单机或分布式 缓存需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木梓辛铭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值