1.首先我们在启动类上加上注解@EnableCaching开启缓存
@EnableCaching //开启缓存
public class SpringDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
}
2.然后我们可以在所需要的方法上加上@Cachable注解进行缓存,该注解有以下可选项
cacheNames = "product" //缓存名
key = "固定值" 或 key = "#sellerid"(可变化的值) //redis缓存中的key
condition = "#sellerid.length > 10" //里面填写表达式,true表示进行缓存,false表示不进行缓存
unless = "#result.getCode() != 0" //和以上相反,当为false时进行缓存,否则不进行缓存
@GetMapping("/list")
@Cacheable(cacheNames = "product",key = "#sellerid",condition = "#sellerid.length() > 2",unless = "#result.getCode() != 0")
public ResultVO list(@RequestParam(value = "sellerid", required = false) String sellerid){
ResultVO resultVO = new ResultVO();
resultVO.setCode(0);
resultVO.setMsg("成功");
ProductVO productVO = new ProductVO();
ProductInfoVO productInfoVO = new ProductInfoVO();
productVO.setProductInfoVOList(Arrays.asList(productInfoVO));
productVO.setCategoryName("粥");
productVO.setCategoryType(1);
productInfoVO.setProductId("1001");
productInfoVO.setProductName("皮蛋粥");
productInfoVO.setProductPrice(new BigDecimal(1.2));
productInfoVO.setProductDescription("好吃的皮蛋粥");
productInfoVO.setProductIcon("https://ss0.baidu.com/73F1bjeh1BF3odCf/it/u=1335713607,299352424&fm=85&s=8D386E974EF26E8427A341710300E07A");
resultVO.setData(Arrays.asList(productVO));
return resultVO;
}
3.@CacheEvict 删除缓存
allEntries = false 清空product里面的所有制
allEntries = true 默认值,删除key对应的值
/**
* 保存/更新
* @param form
* @param bindingResult
* @param map
* @return
*/
@PostMapping("/save")
@CacheEvict(cacheNames = "product",key = "123",allEntries = true)
public ModelAndView save(@Valid ProductForm form,
BindingResult bindingResult,
Map<String,Object> map){
if (bindingResult.hasErrors()){
map.put("msg",bindingResult.getFieldError().getDefaultMessage());
map.put("url","/seller/product/error");
return new ModelAndView("common/error",map);
}
try{
ProductInfo productInfo = new ProductInfo();
if (!StringUtils.isEmpty(form.getProductId())){
productInfo = productService.findOne(form.getProductId());
}else{
form.setProductId(KeyUtils.getUniqueKey());
}
BeanUtils.copyProperties(form,productInfo);
productService.save(productInfo);
}catch (SellException e){
map.put("msg",e.getMessage());
map.put("url","/seller/product/index");
return new ModelAndView("common/error",map);
}
map.put("url","/seller/product/list");
return new ModelAndView("common/success",map);
}
4. @CachePut
每次执行都会执行方法,无论缓存里是否有值,同时使用新的返回值的替换缓存中的值。这里不同于@Cacheable:@Cacheable如果缓存没有值,从则执行方法并缓存数据,如果缓存有值,则从缓存中获取值
5.@CacheConfig
@CacheConfig: 类级别的注解:如果我们在此注解中定义cacheNames,则此类中的所有方法上 @Cacheable的cacheNames默认都是此值。当然@Cacheable也可以重定义cacheNames的值