苍穹外卖项目的学习笔记
一、常用注解:
具体用法例子:
@EnableCaching直接加在启动类上就行
@Cacheable(cacheNames= "setmealCache",key="categoryId")
1、@CachePut(cacheNames="userCache",key="#形参.id")
2、或者@CachePut(cacheNames="userCache",key="#result.id")
3、或者@CachePut(cacheNames="userCache",key="#p0.id")
4、或者@CachePut(cacheNames="userCache",key="#a0.id")
5、或者@CachePut(cacheNames="userCache",key="#root.args[0].id")
3/4/5的key是第一个参数的意思,推荐使用第一种
CacheEvict(cacheNames="userCache",key="#形参")//删除单个缓存数据,精确删除
CacheEvict(cacheNames="userCache",allEntries=true)//批量删除
二、具体实现案例
导入maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
在启动类上加入@EnableCaching注解(如图第三行),开启缓存注解功能
@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@EnableCaching//开启缓存注解功能
@Slf4j
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
log.info("server started");
}
}
在用户端接口Controller的需要用到缓存数据的具体方法上加入@Cacheable注解,eg:
/**
* 条件查询
*
* @param categoryId
* @return
*/
@GetMapping("/list")
@ApiOperation("根据分类id查询套餐")
@Cacheable(cacheNames= "setmealCache",key="categoryId")
public Result<List<Setmeal>> list(Long categoryId) {
Setmeal setmeal = new Setmeal();
setmeal.setCategoryId(categoryId);
setmeal.setStatus(StatusConstant.ENABLE);
List<Setmeal> list = setmealService.list(setmeal);
return Result.success(list);
}
在管理端接口setmealController的需要用到删除缓存数据的方法上加入@CacheEvict注解,eg:
/**
* 新增套餐
* @param setmealDTO
* @return
*/
@PostMapping
@ApiOperation("新增套餐")
@CacheEvict(cacheNames = "setmealCache",key="#setmealDTO.categoryId")
public Result save(@RequestBody SetmealDTO setmealDTO) {
setmealService.saveWithDish(setmealDTO);
return Result.success();
}