欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > Spring Cache的详细使用

Spring Cache的详细使用

2025/9/16 0:03:28 来源:https://blog.csdn.net/weixin_52580607/article/details/147896880  浏览:    关键词:Spring Cache的详细使用

Spring Cache

  • Spring Cache 详解及应用场景
    • 1. Spring Cache 的核心概念
      • 1.1 核心接口
      • 1.2 核心注解
    • 2. Spring Cache 的应用场景
      • 2.1 数据库查询缓存
      • 2.2 接口响应缓存
      • 2.3 方法结果缓存(计算密集型)
      • 2.4 缓存更新与失效
    • 3. Spring Cache 的缓存实现
    • 4. 最佳实践 & 注意事项
    • 总结

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: redisredis:host: localhostport: 6379
@Configuration
@EnableCaching
public class CacheConfig {@Beanpublic 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 等缓存技术,可以灵活应对 单机或分布式 缓存需求。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词