缓存功能框架---Spring Cache用法介绍

苍穹外卖项目的学习笔记

 一、常用注解:

具体用法例子:

@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();
    }

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值