原理:基于Proxy/AspectJ动态代理技术的AOP思想(面向切面编程)
使用

  1. SpringCache包含两个顶级接口,Cache(缓存)和CacheManager(缓存管理器),顾名思义,用CacheManager去管理一堆Cache。
  2. spring cache实现有基于XML/注解实现AOP;
  3. CacheManager负责对缓存的增删改查, CacheManager的缓存的介质可配置, 如:ConcurrentMap/EhCache/Redis等。当没有加入EhCache或者Redis依赖时默认采用concurrentMap实现的缓存,是存在内存中,重启服务器则清空缓存

pring Cache中的注解主要有如下五个:

  • @Cacheable:缓存数据或者获取缓存数据
  • @CachePut:修改缓存数据
  • @CacheEvict: 清空缓存
  • @CacheConfig:统一配置@Cacheable中的value值
  • @Caching:组合多个Cache注解

1.@Cacheable

先从value中获取为key的缓存,如果存在直接返回;如果不存在则执行方法并返回,且把返回输出存入缓存。(注意:保存的数据是return返回的数据)
主要有三个参数:

  • value:缓存的名称,可以多个 (必填,也可以用@CacheConfig替代)
 @Cacheable(value="testcache")
 @Cacheable(value={"testcache1","testcache2"}
  • key:缓存的 key,按照 SpEL 表达式编写,为空时默认为方法的入参(value相当于缓存空间的名称,而key相当于是一个缓存值的名字)
@Cacheable(value="testcache",key="#id")
  • condition:缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false
@Cacheable(value="testcache",condition="#id.length()>2")

2.@CachePut

根据value中获取为key的缓存,如果存在则修改;不存在则新增
主要是三个参数
value,key,condition如上所示。

注意:保存的数据是return返回的数据,如下返回的有user对象和null,第一个缓存的数据是实体类,第二个缓存的数据是空
在这里插入图片描述
在这里插入图片描述

3.@CacheEvict

根据对应的value和key删除缓存,没有key值则删除value中所有的缓存
主要有五个参数value,key,condition,allEntries,beforeInvocation

  • allEntries:是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存
@CachEvict(value="testcache",allEntries=true)

图一、会清空getData下面所有缓存(allEntries=true则删除所有)
是对的是的
图二、只会清空getData下面key值为id的缓存(没有key默认取入参)
在这里插入图片描述
图三、不会清空任何缓存
allEntries=true

  • beforeInvocation: 是否在方法执行前就清空,缺省为 false,如果指定为
    true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存(注:作用只有一个,就是先清空缓存再执行方法
@CachEvict(value="testcache",beforeInvocation=true)

4.@CacheConfig

相当于把类下面所有方法@Cacheable中的value值放到@CacheConfig注解中,
如果@Cacheable中没有value值则用@Cacheable中的值;如果@Cacheable中有value值则以value值为准。

复制代码
@CacheConfig("testcache")
public class UserServiceImpl implements  UserService{

    @Cacheable
    public Result findById(Long id) {
    }
    
	@Cacheable
    public Result findByIdAndName(Long id,String name) {
    }

5.@Caching

组合注解,可以组合多个注解

@Caching(put = {
	@CachePut(value = "user", key = "#user.id"),
	@CachePut(value = "user", key = "#user.username"),
	@CachePut(value = "user", key = "#user.email")
})
public User save(User user) {
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐