使用@Cacheable 和 @CacheEvict注解进行 redis缓存


前言

在现代应用开发中,缓存是提升性能和响应速度的关键技术。Spring Boot 提供了强大的缓存抽象,简化了缓存的配置和使用。本文将介绍如何使用 @Cacheable 和 @CacheEvict 注解来实现redis缓存的自动管理,包括如何缓存数据以及如何手动清空缓存。


一、 引入依赖

首先,确保你的项目中已经引入了 Spring Boot 缓存和 Redis 相关的依赖。如果你使用 Maven,可以在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>

二、 配置 Redis

application.yml 中配置 Redis 作为缓存存储:

spring:
  cache:
    type: redis
    redis:
      time-to-live: 60000  # 设置缓存过期时间为60秒
  redis:
    host: localhost
    port: 6379

三、启用缓存

在你的 Spring Boot 启动类上添加 @EnableCaching 注解来启用缓存功能:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
    
@SpringBootApplication
@EnableCaching
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

四、创建服务类

定义一个服务类,其中包含缓存操作的方法:

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

@Service
public class BaseCodeService {

    @Cacheable(value = "baseCode", key = "#typeKey")
    public String getBaseCode(String typeKey) {
        try {
            Thread.sleep(2000); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Code for " + typeKey;  // 返回示例值
    }

    @CacheEvict(value = "baseCode", allEntries = true)
    public void clearCache() {
        // 清空"baseCode"缓存中的所有条目
    }

    @CacheEvict(value = "baseCode", key = "#typeKey")
    public void clearSpecificCache(String typeKey) {
        // 清空"baseCode"缓存中key为typeKey的条目
    }
}

五、编写测试类

编写测试类验证缓存和缓存清空功能:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
public class BaseCodeServiceTest {

    @Autowired
    private BaseCodeService baseCodeService;

    @Test
    public void testCacheable() {
        long startTime = System.currentTimeMillis();
        String code1 = baseCodeService.getBaseCode("typeA");
        long firstCallDuration = System.currentTimeMillis() - startTime;

        startTime = System.currentTimeMillis();
        String code2 = baseCodeService.getBaseCode("typeA");
        long secondCallDuration = System.currentTimeMillis() - startTime;

        // 断言两次调用结果相同
        assertEquals(code1, code2);

        // 第一次调用应该比较慢,因为是从原始方法获取的值
        System.out.println("First call duration: " + firstCallDuration + "ms");

        // 第二次调用应该非常快,因为是从缓存中获取的值
        System.out.println("Second call duration: " + secondCallDuration + "ms");

        // 断言第二次调用的时间远小于第一次调用的时间
        assert secondCallDuration < firstCallDuration;
    }

    @Test
    public void testCacheEvict() {
        // 添加到缓存中
        baseCodeService.getBaseCode("typeA");

        // 清空缓存
        baseCodeService.clearCache();

        // 确认缓存被清空
        long startTime = System.currentTimeMillis();
        String code = baseCodeService.getBaseCode("typeA");
        long callDuration = System.currentTimeMillis() - startTime;

        System.out.println("Call duration after cache clear: " + callDuration + "ms");

        // 确认清空后调用的时间较长
        assert callDuration > 2000;  // 应大于模拟的2000ms
    }
}

六、运行测试

运行测试类 BaseCodeServiceTest,确保缓存功能正常工作。第一次调用 getBaseCode 方法会有较长的延迟,第二次调用会从缓存中快速获取结果。调用 clearCache 方法后,再次调用 getBaseCode 将会重新执行耗时操作,验证缓存已被清空。

1、testCacheable()运行结果:

第一次调用耗时: 1641ms
第二次调用耗时:2ms

2、testCacheEvict()运行结果:

清除缓存后调用耗时:2020ms

总结

通过这些步骤,你可以高效地管理和测试 Spring Boot 中的缓存功能。使用 @Cacheable 注解来缓存数据,并使用 @CacheEvict 注解来手动清空缓存,帮助你更好地控制缓存的生命周期和数据一致性。

Spring框架通过Spring Cache提供了一套强大的缓存体系,可以轻松地实现缓存数据,提高应用程序的性能。Spring框架提供了三个主要的注解来实现缓存:@Cacheable、@CachePut和@CacheEvict。 @Cacheable注解用于将方法的结果缓存起来,以便在下次请求时,如果参数相同,则可以直接从缓存中获取结果,而不需要重新计算。该注解适用于如果计算结果比较耗时,或者需要从数据库或其他外部资源中提取数据的情况。 @CachePut注解用于更新缓存中的数据。它与@Cacheable注解类似,但不同的是,它总是更新缓存数据,而不管缓存中是否已经存在该key的值。所以,可以使用这个注解来更新缓存中的数据。 @CacheEvict注解用于从缓存中删除数据。它在需要删除缓存数据的情况下使用。它可以删除指定的key对应的缓存,也可以清空所有缓存数据。 这三个注解都有一个可选参数Named:如果指定了该参数,则缓存使用指定的名称使用。如果未指定,则使用默认的名称。可以使用不同名称的缓存来存储不同类型的数据,并使用不同的缓存策略来控制它们的存储方式。 除了Spring自带的缓存提供者之外,还可以使用其他的缓存提供者,如EhcacheRedis、Memcached等等。在使用缓存时,需要注意的是,不同的缓存提供者之间可能会有不同的限制和性能差异。因此,必须根据实际情况选择最适合的缓存提供者和缓存策略,以获取最好的性能和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值