Spring Boot 之 springcache的使用

一、开启 springcache,启动类添加 @EnableCaching 注解

@SpringBootApplication
@EnableCaching
public class GatheringApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatheringApplication.class, args);
    }
}

二、添加缓存,修改 findById 方法 通过 @Cacheable 添加缓存

    /**
     * 根据ID查询实体
     * @param id
     * @return
     */
    @Cacheable(value = "gathering",key = "#id")
    public Gathering findById(String id) {
        System.out.println("查询次数:"+i++);
        return gatheringDao.findById(id).get();
    }

三、删除缓存,修改 update 和 deleteById 方法 通过 @CacheEvict 删除缓存

/**
     * 修改
     * @param gathering
     */
    @CacheEvict(value = "gathering",key = "#gathering.id")
    public void update(Gathering gathering) {
        gatheringDao.save(gathering);
    }

    /**
     * 删除
     * @param id
     */
    @CacheEvict(value = "gathering",key = "#id")
    public void deleteById(String id) {
        gatheringDao.deleteById(id);
    }

四、执行结果

1、点击了5次查询,只有一次进入了方法体并,访问了数据库。其余4次都是从缓存中取数据。

  查询次数:1   Hibernate: select gathering0_.id as id1_0_0_, gathering0_.address as address2_0_0_ from tb_gathering gathering0_ where gathering0_.id=?

2、执行修改方法

   Hibernate: select gathering0_.id as id1_0_0_, gathering0_.address as address2_0_0_ from tb_gathering gathering0_ where gathering0_.id=?
   Hibernate: update tb_gathering set address=?, city=?, detail=?, endtime=?, enrolltime=?, where id=?

 3、再次查询(点击5次),因为执行 修改方法时,也删除了缓存,所以本次查询可以进入方法体,并交互数据库

   查询次数:2
   Hibernate: select gathering0_.id as id1_0_0_, gathering0_.address as address2_0_0_ from tb_gathering gathering0_ where gathering0_.id=?

 4、执行删除方法

   Hibernate: select gathering0_.id as id1_0_0_, gathering0_.address as address2_0_0_ from tb_gathering gathering0_ where gathering0_.id=?
   Hibernate: delete from tb_gathering where id=?

 5、再次查询(点击5次),因为执行 删除方法时,也删除了缓存,所以本次查询可以进入方法体,并交互数据库,但未查询出结果 

   查询次数:3
    Hibernate: select gathering0_.id as id1_0_0_, gathering0_.address as address2_0_0_ from tb_gathering gathering0_ where gathering0_.id=?

 

转载于:https://www.cnblogs.com/mww-NOTCOPY/p/11312284.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值