Spring Cache基本使用

一、介绍

springCache是一个框架,实现了基于注解的缓存功能,只需要简单的加一个注解,就可以实现缓存

springCache提供了一层抽象,底层可以切换不同的缓存实现,如:

        EHCache

        Caffeine

        Redis

springCache常用注解:

        @EnableCaching :开启缓存注解功能,通常加在实现类上

        @Cacheable : 在方法执行前,先判断缓存中是否有数据,如果有,则返回缓存数据,如果没有数据,调用方法将返回值放到缓存中

        @CachePut :将方法的返回值放到缓存中

        @CacheEvict :将一条或多条数据从缓存中删除

二、项目中应用

1、引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

 2、在启动类加入开启缓存的注解 @EnableCaching

package com.sky;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@EnableCaching //开启缓存的注解
@Slf4j
public class SkyApplication {
    public static void main(String[] args) {
        SpringApplication.run(SkyApplication.class, args);
    }
}

3、 @Cacheable使用

/**
 * 条件查询
 *
 * @param categoryId
 * @return
 */
@GetMapping("/list")
@Cacheable(cacheNames = "userCache", key = "#categoryId")
@ApiOperation("根据分类id查询套餐")
public Result<List<Setmeal>> list(Long categoryId) {

    Setmeal setmeal = new Setmeal();
    setmeal.setCategoryId(categoryId);
    setmeal.setStatus(StatusConstant.ENABLE);
    //根据categoryId和状态查询
    List<Setmeal> list = setmealService.list(setmeal);

    return Result.success(list);
}

4、 @CacheEvict精确清理

/*添加套餐*/
@PostMapping
@AutoFill(OperationType.INSERT)//公共字段自动填充
@CacheEvict(cacheNames = "userCache", key = "#setmeal.categoryId")
public Result add(@RequestBody Setmeal setmeal){
    //插入套餐数据
    setmealService.add(setmeal);

    return Result.success();
}

 

5、@CacheEvict批量清理

 

/*修改售卖状态*/
@PostMapping("/status/{status}")
@CacheEvict(cacheNames = "userCache", allEntries = true)
public Result status(@PathVariable Integer status, Long id){

    //修改数据
    setmealService.updateStatus(status,id);

    return Result.success();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值