SpringCache之 @CachePut的使用

来自:互联网
时间:2021-02-16
阅读:

使用CachePut注解,该方法每次都会执行,会清除对应的key值得缓存(或者更新),

分为以下两种情况:

如果返回值null,下次进行该key值查询时,还会查一次数据库,此时相当于@CacheEvict注解;

如果返回值不为null,此时会进行该key值缓存的更新,更新缓存值为返回的数据;

分析:情况一返回值为null:

//使用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());
    return null;
  }

情况二返回值不为null: 

先进行数据id为1的查询,发现下次查询id为1的数据不会再查询DB,直接走缓存;

此时进行id为1数据更新操作,并且返回值为null;

进行id为1的数据查询,发现此时id为1缓存不存在,进行DB查询;

 //使用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());
    //return null;
  }

先进行数据id为1的查询,发现下次查询id为1的数据不会再查询DB,直接走缓存;

此时进行id为1数据更新操作,返回值不为null;

进行id为1的数据查询,发现此时id为1缓存被更新为更新的数据,且没有进行DB查询操作;

补充:@CachePut和@Cacheable的区别

@CachePut负责增加缓存

@Cacheable负责查询缓存,如果没查到,则将执行方法,并将方法的结果增加到缓存

以上为个人经验,希望能给大家一个参考,也希望大家多多支持免费资源网。如有错误或未考虑完全的地方,望不吝赐教。

返回顶部
顶部