这篇文章主要介绍了SpringCache之 @CachePut的使用,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
使用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="Ma<em style="color:transparent">来源[email protected]搞@^&代*@码网</em>nager",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负责查询缓存,如果没查到,则将执行方法,并将方法的结果增加到缓存
以上就是SpringCache之 @CachePut的使用的详细内容,更多请关注gaodaima搞代码网其它相关文章!