gpt4 book ai didi

SpringCache之 @CachePut的使用

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 27 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章SpringCache之 @CachePut的使用由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

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

分为以下两种情况:

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//使用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查询,

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//使用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负责查询缓存,如果没查到,则将执行方法,并将方法的结果增加到缓存 。

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

原文链接:https://blog.csdn.net/MrLiar17/article/details/88253702 。

最后此篇关于SpringCache之 @CachePut的使用的文章就讲到这里了,如果你想了解更多关于SpringCache之 @CachePut的使用的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com