SpringBoot缓存注解使用

背景

除了 RedisTemplate 外, 自Spring3.1开始,Spring自带了对缓存的支持。我们可以直接使用Spring缓存技术将某些数据放入本机的缓存中;Spring缓存技术也可以搭配其他缓存中间件(如Redis等)进行使用,将某些数据写入到缓存中间件(缓存中间件可能在其他机器上)中。

常用缓存

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

使用

1. 添加依赖并配置redis信息

在 pom.xml 中添加依赖

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

在 application.yml 文件中添加依赖

spring:
  redis:
    host: 192.168.**.***
    port: ****
    password: ****
    database: 1

2. 在启动类上添加 @EnableCaching 注解

在这里插入图片描述

3. 使用缓存注解

package com.itheima.controller;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping
    // 使用 @CachePut 添加缓存数据, key 的生成: userCache::user.id,例如 userCache::12
    @CachePut(cacheNames = "userCache", key = "#user.id")
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

    @DeleteMapping
    // 删除指定缓存
    @CacheEvict(cacheNames = "userCache", key = "#id")
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

	@DeleteMapping("/delAll")
    // 删除所有缓存
    @CacheEvict(cacheNames = "userCache", allEntries = true)
    public void deleteAll(){
        userMapper.deleteAll();
    }

    @GetMapping
    // key 的生成: userCache::12
    @Cacheable(cacheNames = "userCache", key = "#id")
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

}


4. 结果

这里以 @CachePut 注解为例演示结果。
向表中添加数据后可以看到成功将新用户信息添加到了缓存中。
在这里插入图片描述
缓存中信息
在这里插入图片描述

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,你可以使用`@Cacheable`注解来启用缓存功能,并且可以与Redis集成来实现缓存。 `@Cacheable`注解可以应用在方法上,用于指示Spring在调用此方法之前,首先从缓存中查找对应的数据。如果缓存中有数据,则直接返回缓存中的数据,不再执行方法体内的代码。如果缓存中没有数据,则会执行方法体内的代码,并将返回值存储到缓存中。 要使用`@Cacheable`注解,你需要在启动类上添加`@EnableCaching`注解来启用缓存功能。此外,还需要配置Redis作为缓存的存储介质。 首先,引入依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,在`application.properties`或`application.yml`中配置Redis连接信息: ```yaml spring.redis.host=your_redis_host spring.redis.port=your_redis_port ``` 然后,在需要使用缓存的方法上添加`@Cacheable`注解,指定缓存的名称: ```java @Cacheable("myCache") public String getData(String key) { // 从数据库或其他数据源获取数据的逻辑 } ``` 以上示例中,方法`getData()`会先从名为`myCache`的缓存中查找数据,如果找到则直接返回缓存中的数据;如果没有找到,则执行方法体内的代码,并将返回值缓存起来。 注意:为了使`@Cacheable`注解生效,需要在启动类上添加`@EnableCaching`注解。 这样,你就可以在Spring Boot使用Redis缓存注解来提高应用的性能了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值