SpringCache
SpringCache 介绍
SpringCache 是一个框架,实现了基于注解的缓存功能,只需要加一个 简单的注解,就能实现缓存功能。
SpringCache 底层提供了 一层抽象,底层可以切换不同的 cache 来实现。具体就是通过 CacheManager 接口来统一不同的缓存技术
CacheManager 是 Spring 提供的各种缓存技术的抽象接口
针对不同的 缓存技术需要实现不同的CacheManager
CacheManager | 描述 |
---|---|
EhCacheManager | 使用 EhCache 作为缓存技术 |
GuavaCacheManager | 使用 Google 的 GuavaCache 作为缓存技术 |
RedisCacheManager | 使用 Redis 作为缓存技术 |
SpringCache 常用注解
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能 |
@Cachable | 在方法执行前 spring 先查看缓存中是否有数据,如果有数据,将直接返回缓存数据,如果没有数据,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
-
@CachePut : 将方法返回值放入缓存
-
@CachePut(value = "userCache", key = "#user.id")
-
value : 缓存的名称,每个缓存名称下可以有多个 key
-
key : 缓存的 key
-
-
@CacheEvict : 将数据从缓存中删除
-
@CacheEvict(value = "userCache", key = "#id")
-
**allEntries : ** 删除该 value 下的所有缓存数据
-
-
@Cacheable :
-
@Cacheable(value = "userCache", key = "#id")
-
condition : 条件,满足条件时才缓存
-
@Cacheable(value = "userCache", key = "#id", condition = "#result != null")
-
但是 Cacheable 注解不能使用 result,所以不会生效
-
-
unless : 满足条件时不缓存
-
@Cacheable(value = "userCache", key = "#id", unless = "#result == null")
#result == null 时,就 不会 缓存
-
-
在 springboot 项目中,使用缓存技术只需在 项目中导入相关的依赖包,并在启动类上使用 @EnableCaching
开启缓存技术即可
例如 使用Redis 作为缓存技术,只需要导入 sprigboot data redis
的 maven 坐标即可