
springboot缓存注解
# SpringBoot 缓存注解技能
## 技能描述
为SpringBoot项目添加基于Redis的缓存注解功能,通过 `@CacheResult` 注解实现方法返回值的缓存。
## 使用场景
当用户需要在已有的SpringBoot项目基础上添加缓存功能时使用此技能。
## 依赖关系
此技能依赖于 springboot-init 技能生成的基础项目结构。
## 功能说明
### 注解参数
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| keyPrefix | String | "project:cache" | 缓存key的前缀 |
| key | String | "" | 普通缓存key |
| spelKey | String | "" | SpEL表达式缓存key |
| cacheTime | int | 1 | 缓存时间 |
| cacheTimeUnit | TimeUnit | TimeUnit.HOURS | 缓存时间单位 |
### Key生成策略
1. **优先使用普通key**: `keyPrefix:key`
2. **次优先使用SpEL**: `keyPrefix:解析SpEL表达式`
3. **默认策略**: `keyPrefix:类全限定名:方法名:AES(参数)`
### 使用示例
```java
// 使用普通key
@CacheResult(keyPrefix = "user:", key = "info")
public User getUser(Long userId) {
// ...
}
// 使用SpEL key
@CacheResult(keyPrefix = "user:", spelKey = "#userId")
public User getUser(Long userId) {
// ...
}
// 使用默认key (MD5加密参数)
@CacheResult(cacheTime = 30, cacheTimeUnit = TimeUnit.MINUTES)
public User getUser(Long userId) {
// ...
}
```
## 生成的依赖
- cn.hutool:hutool-all (MD5加密工具)
- spring-boot-starter-data-redis (Redis缓存)
- spring-boot-starter-aop (AOP切面支持)
## 生成的配置文件
### pom.xml
更新添加以下依赖:
- hutool-all
- spring-boot-starter-data-redis
- spring-boot-starter-aop
### application.yml
更新添加Redis配置:
```yaml
spring:
data:
redis:
host: localhost
port: 6379
password:
database: 0
timeout: 3000ms
```
## 生成的文件
| 文件路径 | 说明 |
|----------|------|
| annotation/CacheResult.java | 缓存注解 |
| common/CacheNullValue.java | null值标记类 |
| util/CacheKeyGenerator.java | Key生成工具类 |
| aspect/CacheResultAspect.java | 缓存AOP切面 |
| config/RedisConfig.java | Redis配置类 |
## 脚本执行
执行脚本添加缓存注解功能:
```bash
python .trae/skills/springboot-cache/scripts/cache_annotation.py
将提示词发送给你的 AI 安装该 skills
请根据 https://skillhub.cn/install/skillhub.md,安装 @user_faca7523/springboot-cache。
将提示词发送给你的 AI 安装该 skills
请根据 https://skillhub.cn/install/skillhub.md,安装 @user_faca7523/springboot-cache。














下载 Zip 包安装
