【十次方】Springboot中使用SpringCache做缓存

Spring全家桶+分布式微服务(十次方项目学习)

十次方学习交流qq群:672373393

 其实在sptringboot中本身提供了一个缓存SpringCache,相比redis更加的简单,但是相对的功能也没有redis强大。如果没有其它特别的需求,比如说设定缓存时间等。那么我们就可以直接使用springcache将会更加简单,多用于find查询中。

如何使用?

1.在启动类上添加注解

@EnableCaching //表示我要使用springboot的缓存  springcache

2. 上代码

我们还是那findById来说,springcache直接在方法上加上注解

@Cacheable 其中参数value是作为全局唯一id,key则是作为value中的子id,两个参数都必须要写
这里注意用#可以拿到方法参数值 #后面接参数名就可以了
	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	@Cacheable(value = "gathering",key = "#id")  //存springcache,value表示在cache中全局名称,key才是id,用#可以拿到参数值
	public Gathering findById(String id) {
		return gatheringDao.findById(id).get();
	}

同理,我们如果对数据进行了修改,也需要更改缓存中的数据,这里用到注解

@CacheEvict 参数与@Cacheable一致
	/**
	 * 修改
	 * @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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值