SpringCache之 @CachePut的使用

网友投稿 768 2023-02-12

SpringCache之 @CachePut的使用

SpringCache之 @CachePut的使用

使用CachePut注解,该方法每次http://都会执行,会清除对应的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负责查询缓存,如果没查到,则将执行方法,并将方法的结果增加到缓存

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:@Cacheable 拼接key的操作
下一篇:app运营模式分红(2020分红模式app赚钱软件)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~