Spring Cache的详细使用

Spring Cache

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

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

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

2.2 接口响应缓存

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

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

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

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

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

2.4 缓存更新与失效

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

java 复制代码
@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)

yaml 复制代码
# application.yml
spring:
  cache:
    type: redis
  redis:
    host: localhost
    port: 6379
java 复制代码
@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 等缓存技术,可以灵活应对 单机或分布式 缓存需求。

相关推荐
GJCTYU8 分钟前
spring中@Transactional注解和事务的实战理解附代码
数据库·spring boot·后端·spring·oracle·mybatis
柑木18 分钟前
Rust-开发应用-如何实现单例
后端·rust
艾迪的技术之路19 分钟前
redisson使用lock导致死锁问题
java·后端·面试
struggleupwards20 分钟前
golang中defer的小坑
后端·go
hai99long21 分钟前
最终一致性分布式事务的解决方案
后端
独立开阀者_FwtCoder26 分钟前
国外最流行的 UI 组件库!适配 Vue、React、Angular!
前端·vue.js·后端
勇哥java实战分享29 分钟前
聊聊 RocketMQ 4.X 知识体系
后端
CodeSheep34 分钟前
小米汽车这薪资是认真的吗?
前端·后端·程序员
今天背单词了吗98037 分钟前
算法学习笔记:8.Bellman-Ford 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·后端·算法·最短路径问题