Spring Cache快速入门

简介

Spring Cache 是 Spring 框架提供的一种缓存抽象,它允许开发者以一种声明式的方式来使用缓存,而不需要关心底层的缓存实现技术。Spring Cache 的核心org.springframework.cache.Cache org.springframework.cache.CacheManager 接口,它们定义了缓存操作的基本规范 。

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

  • EHCache
  • Caffeine
  • Redis

要开始使用 Spring Cache,你需要在你的项目中添加 Spring Context 模块的依赖,如果你使用的是 Spring Boot,可以通过添加 spring-boot-starter-cache 来快速集成缓存功能 。

使用

要开始使用 Spring Cache,你需要在你的项目中添加 Spring Context 模块的依赖,如果你使用的是 Spring Boot,可以通过添加 spring-boot-starter-cache 来快速集成缓存功能 。

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

常用注解

注解说明
@EnableCaching开启缓存注解功能,通常加在启动类上
@Cacheable在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中
@CachePut将方法的返回值放到缓存中
@CacheEvict将一条或多条数据从缓存中删除

使用展示

    @PostMapping
    @CachePut(cacheNames = "user",key = "#user.id")//使用Spring Cache缓存数据,key的生成:user::id
//    @CachePut(value = "user",key = "#result.id")//使用Spring Cache缓存数据,key的生成:user::result.id                   result是返回值
//    @CachePut(value = "user",key = "#p0.id")//使用Spring Cache缓存数据,key的生成:user::p0.id                           p0是第一个方法参数中的id
//    @CachePut(value = "user",key = "#a0.id")//使用Spring Cache缓存数据,key的生成:user::a0                              p0是第一个方法参数中的id
//    @CachePut(value = "user",key = "#root.args[0].id")//使用Spring Cache缓存数据,key的生成:user::root.args[0].id       root.args[0].id是第一个方法参数中的id
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }
	@DeleteMapping
    @CacheEvict(cacheNames = "user",key = "#id")
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }
	@DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "user",allEntries = true)
    public void deleteAll(){
        userMapper.deleteAll();
    }
    @GetMapping
    @Cacheable(cacheNames = "user",key = "#id")
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jacky-YY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值