黑马十次方项目day02-18之springcache的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33229669/article/details/86432494

启动类上加注解

加上@EnableCaching注解,表示要使用sringboot的缓存

@SpringBootApplication
@EnableCaching
public class GatheringApplication {

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

	@Bean
	public IdWorker idWorkker(){
		return new IdWorker(1, 1);
	}
	
}

service

把数据存入springcache和从springcache读取数据
在方法上,使用@Cacheable(value = "gathering",key = "#id")注解即可.
value = "gathering"类似于一个大key,必须写上,否则会报错.
key = "#id",相当于一个小key. 用#id来表示, 会读取当前的id值

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

删除缓存
在修改和删除的方法上,加上删除缓存的注解.
@CacheEvict注解用于删除springcache的缓存,
在修改的方法中, key用的是gathering.id.即对象.属性.因为此方法的形参传递的是对象,因此要用对象.属性的方式,来获取key值.

/**
	 * 修改
	 * @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);
	}

测试

启动com.tensquare.gathering.GatheringApplication类.
发送get请求http://localhost:9005/gathering/1 根据id进行查询.
第一次查询是进数据库的,有sql语句的打印,第二次查询就没有sql语句了, 直接用的是缓存中的数据.
发送修改活动的put请求http://localhost:9005/gathering/1
在请求体中传递参数

{
    "id": "1",
    "name": "测试活动11111",
    "summary": "喝茶看电影,不亦乐乎",
    "detail": "喝茶看电影,不亦乐乎"
  }

修改成功后, 会再次从数据库中读取数据, 因为缓存中的数据被删除了.

Redis与springcache的区别

  1. Redis可以设置key的过期时间,springcache不能
  2. springcache使用较为Redis简便,直接用注解即可.而且为spring自带的,无需引入额外的资源
  3. Redis api丰富,能使用的场景较多,且能搭建集群主从备份. 在实际公司中,使用Redis作为缓存更为普遍

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/86432494
今日推荐