好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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的使用的详细内容...

  阅读:20次