SpringBoot缓存机制

springboot缓存——@Cache

一、JSR107规范
JSR107规范定义了很多接口(这里不多讲,可以去百度了解jsr107规范)
在这里插入图片描述
二、spring缓存抽象(cache的注解底层调用aop)
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

三、快速体验springboot的缓存
(1)开启与注解的缓存(application启动类上加入)
@EnableCaching
(2)详细说明(念经):
将方法的运行结果进行缓存:以后再要相同的数据,直接从缓存中获取,不再调用方法走dao层接口:
CacheManager管理多个cache组件,对缓存的真正CRUD操作在cache组件中,每一个缓存组件有自己唯一的名字;
几个属性:
cacheNames/value:指定缓存组件的名字(例如对于user对象的缓存,缓存组件可以命名为user)
key:缓存数据使用的key,可以用它来制定。默认是使用方法参数的值 1-方法的返回值
编写SpEL; #id;参数id的值,#a0 、#p0、 #root.args[0]
如果不指定,则缺省按照方法的所有参数进行组合。例如:
@Cacheable(value=”testcache”,key=”#id”)
keyGenerator:key的生成器;可以指定key生成器组件id
key/keyGenerator:二选一使用
cacheManager:指定缓存管理器,或者cacheResolver指定获取解析器
condition:指定符合条件的情况下才缓存
condition="#id>0"当参数id大于0时才执行缓存操作
condition="#a0>1"当第一个参数大于1时才执行缓存
unless:否定缓存,当unless指定的条件true,方法的返回值就不会指定;可以获取结果
进行判断 unless="#resultnull"
unless="#a0
2":如果第一个参数的值是2,结果不缓存
sync:是否使用异步缓存方式(默认是同步false,因为异步true模式下不支持unless条件)

(3)标注缓存注解即可(如果在类上加上@CacheConfig(cacheNames=“emp”),那么该类里面所有的cache注解的value都不用写,都会是emp)

增——@Cacheable
(执行目标方法前先根据key查询对应的缓存,有则不执行目标方法,无则执行目标方法,并且将目标方法结果放入缓存中)
例子:

//取第一个参数的job对象的id属性执行缓存操作
@Cacheable(value = "emp",key = "#p0.id")//目标方法参数是对象(#job.id也行)
public NewJob save(NewJob job) {
    newJobDao.save(job);
    return job;
}

@Cacheable(value="users", key="#id")//目标方法参数是id,key可以直接写id
   public User find(Integer id) {
      returnnull;
   }

删——@CacheEvict
(根据参数删除缓存中对应的keyvalue)
例子:

//清除一条缓存,key为要清空的数据
@CacheEvict(value="emp",key="#id")
public void delect(int id) {
    newJobDao.deleteAllById(id);
}

//方法调用后清空所有缓存
@CacheEvict(value="accountCache",allEntries=true)
public void delectAll() {
    newJobDao.deleteAll();
}

//方法调用前清空所有缓存
@CacheEvict(value="accountCache",beforeInvocation=true)
public void delectAll() {
    newJobDao.deleteAll();
}

改——@CachePut
(相当于先执行一遍@CacheEvict清除缓存,再执行一遍@Cacheable添加缓存——实现更改缓存的功能)
例子:
如果返回值null,下次进行该key值查询时,还会查一次数据库,此时相当于@CacheEvict注解;
如果返回值不为null,此时会进行该key值缓存的更新,更新缓存值为返回的数据;

//使用Redis缓存
    @Cacheable(value="Manager",key="#id")
    public User findById(Integer id) {
        System.out.println("---查数据库DB-----");
        return userMapper.selectByPrimaryKey(id);
    }
 
    @CachePut(value="Manager",key="#manager.getId()")
    //@CacheEvict(value="Manager",key="#manager.getId()")//清除数据
    public User update(User manager) {
        userMapper.updateByPrimaryKeySelective(manager);
        return userMapper.selectByPrimaryKey(manager.getId());
    }

复杂注解——@Caching(可以一次性执行多条注解)
只要执行了该目标方法,就会一定执行@Caching中的@CachePut,但是如果返回值为空,那么就会报错,假设执行成功,那么缓存中就会有key为id,value为emp的缓存

@Caching(
            cacheable = {
                    @Cacheable(value = "emp",key = "#lastName")
            },
            put = {
                    @CachePut(value = "emp",key = "#result.id"),
                    @CachePut(value = "emp",key = "#result.email"),
            }
    )
    @ResponseBody
    @RequestMapping("/emp/lastName/{lastName}")
    public Employee getEmpByLastName(@PathVariable("lastName") String lastName){
        Employee employee = employeeService.getEmpByLastName(lastName);
        return employee;
    }

(4)Cache的SpEL表达式

(5)源码分析(继续念经——其实没啥用,稍微知道就行)
原理
1、自动配置类:CacheAutoConfiguration
2、缓存的配置类
org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
org.springframework.boot.autoconfigure.cache.HaztLcastCacheConfiguration
org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration(默认)
org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
3、哪个配置类默认生效:SimpleCacheConfiguration
4、给容器注册一个CocheManager:ConcurrentMapConfiguration
5、可以获取和创建一个ConcurrentMapConfiguration类型的缓存组件,他的作用将数据保存在ConcurrentMap中
6、根据cache的相关注解,Cacheable,CachePut,CacheEvict等运行,这里省略细节

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值