文章目录
前言
在现代应用开发中,缓存是提升性能和响应速度的关键技术。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 注解来手动清空缓存,帮助你更好地控制缓存的生命周期和数据一致性。