springboot自带的缓存@EnableCaching

一般使用springboot自带缓存时,直接就在启动类里添加注解@EnableCaching 。@EnableCaching她有两个经常使用的方法

1,@Cacheable添加缓存

  
   这里的value 是该缓存的名称,可以随意写,而key要严格按照查询条件来写,比如这里是查询条件id.

   @Cacheable(value = "gathering",key = "#id")
	public Gathering findById(String id) {
		return gatheringDao.findById(id).get();
	}

 查询数据库已有的数据,第一次缓存没有该数据,直接走数据库,然后存入缓存

 第二次查询该数据,发现缓存中存在key已有的数据,直接走缓存不走数据库

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

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

Redis可以设置过期时间,springboot自带的缓存不可以。

 

Guess you like

Origin blog.csdn.net/qq_39772439/article/details/121030734