一、SpringCache 是什么?
SpringCache 是 Spring 框架自带的一套 注解式缓存抽象机制,它屏蔽了底层缓存实现(如内存、Redis、Ehcache 等),开发者只需关注业务逻辑和注解,缓存细节 Spring 帮你搞定。
一句话总结:
用最少的代码,实现缓存功能!
二、为什么说 SpringCache 比 Redis 更好用?
当然这里的“更好用”,是指 “更适合日常项目快速开发”,而不是性能碾压 Redis。
✅ 1. 零配置上手快
你只需要一行注解,就能把某个方法的结果缓存起来:
@Cacheable("user")
public User getUserById(Long id) {
return userRepository.findById(id);
}
第一次调用走数据库,结果会缓存起来;
第二次再调,直接返回缓存数据,完全不用你手动操作缓存逻辑!
✅ 2. 多种缓存实现切换自如
SpringCache 默认支持:
- • EhCache、Caffeine、Guava 等内存缓存
要用 Redis?只需在配置文件改一下缓存类型即可:
spring:
cache:
type: redis
业务代码不改一行!
✅ 3. 支持自动过期、条件缓存等高级用法
你还可以自定义缓存条件:
@Cacheable(value = "user", condition = "#id > 100")
自动失效也可以控制(结合配置或 Redis 实现):
@Cacheable(value = "user", key = "#id", unless = "#result == null")
支持缓存更新、缓存删除:
@CachePut("user")
@CacheEvict("user")
功能相当强大!
✅ 4. 轻量级,性能损耗低
在很多内网系统、小中型项目中,其实根本不需要 Redis 的网络通信与部署成本。
直接用 SpringCache + 本地缓存就能满足高并发读写。
更轻、更快、更省事!
三、SpringCache 实战例子
以用户查询为例:
@Service
publicclassUserService {
@Cacheable(value = "user", key = "#id")
public User getUserById(Long id) {
// 只查一次数据库
return userRepository.findById(id);
}
@CacheEvict(value = "user", key = "#id")
publicvoiddeleteUser(Long id) {
// 删除用户时清除缓存
userRepository.deleteById(id);
}
@CachePut(value = "user", key = "#user.id")
public User updateUser(User user) {
// 更新用户并刷新缓存
return userRepository.save(user);
}
}
你只关注业务,缓存自动处理!
四、适合使用 SpringCache 的场景
一句话:小而美的缓存需求,SpringCache 完美胜任!
小结:
如果你只是想快速为接口加个缓存,不想引入复杂的 Redis,那 SpringCache 可能真的是比 Redis 更好用的选择!