SpringBoot 中 cache缓存的使用

SpringBoot 中 cache缓存的使用

1、pom.xml导入依赖 cache依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、SpringBoot启动类上使用 @EnableCaching 注解 开启 cache 缓存应用
@EnableCaching
@SpringBootApplication
public class SpringbootMybaitsApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybaitsApplication.class, args);
    }
}
3、在service 层中的方法上使用 cache 缓存相关注解
@Service
public class DepartService {

    @Autowired
    private DepartMapper departMapper;

    @Cacheable(value = "dep",key = "#id")
    public Department getDepartment(Integer id) throws SQLException {
        System.out.println("执行了查询方法");
        return departMapper.getDepartmentById(id);
    }

    @CachePut(value = "dep",key = "#department.id")
    public Department updateDepartment(Department department){
        System.out.println("执行了更新方法");
        departMapper.updateDepartment(department);
        return department;
    }

    @CacheEvict(value = "dep",key = "#id")
    public String deleteDepartment(Integer id){
        System.out.println("执行了删除方法");
        departMapper.daleteDepartmentById(id);
        return "success";
    }
}

@Cacheable 注解 标注在查询方法上,开启缓存,方法执行之前会去缓存中查询数据,如果缓存中没有,才会执行方法查询数据。

  • value 指定缓存名。

  • key 指定缓存储存的key (缓存中数据储存是以 key-value 方式,value 储存方法返回的对象)。

@CachePut 注解 标注在更新方法上,用于更新缓存。

  • value 指定缓存名。

  • key 指定缓存更新的key (缓存中数据储存是以 key-value 方式,value 储存方法返回的对象)。

@CacheEvict 注解 标注在删除方法上,用于删除换成

  • value 指定缓存名。

  • key 指定缓存删除的key (缓存中数据储存是以 key-value 方式,value 储存方法返回的对象)。

@CacheConfig 注解 标注在上,可以将缓存公共熟悉提取出来一起配置。(例如:将 前三个注解的 value 熟悉取出来使用 @CacheConfig(cacheNames = “dep”) 标注在类上)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值