常用缓存实现与配置
2025/9/17大约 3 分钟
Spring Cache 常用缓存实现(Caffeine/Redis)与配置
前置知识
建议你已掌握 Spring Cache 注解用法与基础配置。
目录
Caffeine 与 Redis 简介
- Caffeine:高性能本地缓存库,基于 Java,支持多种淘汰策略,适合单机热点数据缓存。
- Redis:高性能分布式缓存数据库,支持持久化、发布订阅、丰富数据结构,适合分布式、跨服务缓存。
优缺点与适用场景
实现 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
Caffeine | 极快、无网络延迟、简单易用 | 仅本地缓存,重启丢失 | 单机热点、临时数据 |
Redis | 分布式、持久化、功能丰富 | 需独立部署、网络延迟 | 多实例共享、分布式缓存 |
依赖与配置
1. Maven 依赖
<!-- Caffeine -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. application.yml 配置
Caffeine 示例
spring:
cache:
type: caffeine
cache-names: user,product
caffeine:
spec: maximumSize=1000,expireAfterWrite=10m
Redis 示例
spring:
cache:
type: redis
cache-names: user,product
redis:
host: localhost
port: 6379
password: yourpassword # 如有
timeout: 2000ms
常用参数说明
参数 | 说明 | 示例 |
---|---|---|
maximumSize | 最大缓存条数 | 1000 |
expireAfterWrite | 写入后过期时间 | 10m |
expireAfterAccess | 访问后过期时间 | 5m |
host/port | Redis 主机端口 | localhost/6379 |
timeout | 连接超时 | 2000ms |
实战代码示例
Caffeine 缓存示例
@Service
public class ProductService {
@Cacheable(value = "product", key = "#id")
public Product getProductById(Long id) {
// ...数据库查询
}
}
Redis 缓存示例
@Service
public class UserService {
@Cacheable(value = "user", key = "#id")
public User getUserById(Long id) {
// ...数据库查询
}
}
切换与多级缓存
- 切换实现只需修改
spring.cache.type
,无需改动业务代码 - Spring Cache 支持自定义多级缓存(如本地+Caffeine+Redis)
- 多级缓存需自定义 CacheManager,可参考社区方案
多级缓存原理简述
- 先查本地缓存(Caffeine)
- 本地未命中查 Redis
- Redis 未命中查数据库并回填缓存
常见问题与小结
常见问题
- 缓存不生效:检查 type、依赖、配置、注解
- Redis 连接失败:检查 host/port/password、防火墙
- Caffeine 缓存丢失:重启服务缓存清空,需持久化用 Redis
- 多级缓存不一致:需保证本地与分布式缓存同步
- Caffeine 适合本地热点,Redis 适合分布式共享
- 切换实现简单,推荐结合业务场景灵活选用
- 后续将介绍缓存失效、过期、清理与高级用法
本文为 Spring Cache 系列教程第二篇,后续将介绍缓存失效、过期与高级用法,敬请期待!