一、启动类上面加一个注解@EnableCaching
例如
@SpringBootApplication
@EnableCaching
public class SellApplication {
public static void main(String[] args) {
SpringApplication.run(SellApplication.class, args);
}
}
注意:如果无法找到注解则在pom.xml里面引入此依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
二、在要实现缓存方法上加上注解@Cacheable,因为方法返回的对象必须能序列化,所以方法返回的对象必须实现implements Serializable
例如
@GetMapping("/list")
@Cacheable(cacheNames = "product",key = "123")
public ResultVo list(){
//获取所有上架商品
List<ProductInfo> productInfoList = productInfoService.findUpAll();
ResultVo resultVo = new ResultVo();
resultVo.setCode(0);
resultVo.setMsg("查询成功");
resultVo.setData(productVoList);
return resultVo;
}
三、在数据跟新的方法上加入注解@CacheEvict实现清除缓存
例如:
@PostMapping("/save")
@CacheEvict(cacheNames = "product",key = "123")
public ModelAndView save(@Valid ProductForm productForm, BindingResult bindingResult, Map<String,Object> map){
map.put("url","/sellers/product/list");
map.put("msg","商品修改成功");
return new ModelAndView("order/success",map);
}
如果返回的对象和缓存方法返回的对象一样的推荐使用@CachePut,一般都是用在业务层的方法上