Spring Cache 操作详解

Spring Cache 操作详解

在现代的应用程序中,缓存是提升性能、减少数据源压力的重要手段之一。Spring Boot 提供了一个简洁的缓存抽象框架——spring-boot-starter-cache,而 Redis 作为一个高性能的内存数据库,是缓存实现的理想选择。本文将介绍如何结合 Spring Boot Starter Cache 与 Redis 来实现缓存管理。

1. 添加依赖

首先,在 Spring Boot 项目中集成 Redis 和缓存功能,需要在 pom.xml 中添加相关依赖。

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

spring-boot-starter-cache 提供了 Spring 的缓存抽象,而 spring-boot-starter-data-redis 使我们能够使用 Redis 作为缓存存储。

2. 配置 Redis 连接

application.ymlapplication.properties 中配置 Redis 连接信息。以下是使用 application.yml 的示例:

spring:
  redis:
    host: localhost
    port: 6379
    password: yourpassword  # 如果没有密码可以省略
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
  cache:
    type: redis  # 将缓存类型指定为 redis

以上配置告诉 Spring Boot 使用 Redis 作为缓存存储,并配置了 Redis 连接的主机、端口和连接池。

3. 启用缓存功能

在主启动类或配置类中,添加 @EnableCaching 注解来开启 Spring Boot 的缓存支持:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableCaching
public class CacheApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(CacheApplication.class, args);
    }
}

@EnableCaching 将启用缓存机制,允许在应用程序中使用缓存注解。

4. 使用缓存注解

Spring 提供了一系列注解用于缓存操作,其中最常用的是 @Cacheable@CachePut@CacheEvict。下面通过示例介绍如何使用这些注解。

@Cacheable

@Cacheable 注解用于将方法的返回值缓存起来,之后调用相同参数时将直接返回缓存的内容,而不是再次执行方法。

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {
   

    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
   
        // 模拟耗时操作
        try {
   
            Thread.sleep(3000);
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }
        return new User(id, "John Doe");
    }
}

上面的代码中,getUserById 方法被 @Cacheable 注解标注,缓存名称为 users,缓存的键为方法参数 id。当第一次调用该方法时,结果将被缓存起来,之后使用相同的 id 调用时将直接从缓存中获取数据,而不会再次执行方法逻辑。

@CachePut

@CachePut 用于更新缓存,不会跳过方法执行。它确保方法执行并将结果存入缓存。

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

黑风风

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

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

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

打赏作者

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

抵扣说明:

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

余额充值