在分布式系统或者复杂业务场景中,单次接口调用往往需要更新多个关联缓存,比如用户更新个人信息后,既要更新用户基础信息缓存,也要更新用户权限信息缓存。Spring Cache默认的@Cacheable、@CachePut等注解仅支持单缓存配置,无法满足多缓存同时写入的需求,因此需要扩展Spring Cache的能力来实现该功能。

核心实现思路
实现单次调用写入多缓存的核心思路是自定义一个缓存注解,该注解支持配置多个缓存名称和对应的缓存键,再通过AOP切面拦截标注了该注解的方法,在方法执行成功后,根据注解配置的参数批量操作缓存。整体流程分为三步:定义自定义注解、编写切面处理逻辑、配置缓存管理器。
自定义多缓存注解
首先定义一个@MultiCachePut注解,支持配置多个缓存项,每个缓存项包含缓存名称和缓存键的生成规则。
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MultiCachePut {
// 多个缓存配置
CacheItem[] value();
// 缓存键的前缀,可选
String keyPrefix() default "";
// 是否同步写入,默认异步
boolean sync() default false;
// 单个缓存项配置
@interface CacheItem {
// 缓存名称,对应缓存管理器中配置的缓存
String cacheName();
// 缓存键的SpEL表达式
String key();
// 缓存过期时间,单位秒,0表示不过期
long ttl() default 0;
}
}
编写AOP切面处理逻辑
接下来编写切面类,拦截标注了@MultiCachePut的方法,在方法执行成功后,根据注解配置批量写入缓存。这里使用Spring的CacheManager来获取缓存实例,通过SpEL表达式解析缓存键。
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
public class MultiCachePutAspect {
private final CacheManager cacheManager;
private final ExpressionParser parser = new SpelExpressionParser();
public MultiCachePutAspect(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@Around("@annotation(com.example.demo.annotation.MultiCachePut)")
public Object handleMultiCachePut(ProceedingJoinPoint joinPoint) throws Throwable {
// 执行目标方法
Object result = joinPoint.proceed();
// 方法执行成功后处理缓存
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
MultiCachePut multiCachePut = method.getAnnotation(MultiCachePut.class);
if (multiCachePut == null) {
return result;
}
// 构建SpEL上下文
EvaluationContext context = new StandardEvaluationContext();
String[] paramNames = signature.getParameterNames();
Object[] args = joinPoint.getArgs();
if (paramNames != null) {
for (int i = 0; i < paramNames.length; i++) {
context.setVariable(paramNames[i], args[i]);
}
}
context.setVariable("result", result);
// 处理每个缓存项
for (MultiCachePut.CacheItem item : multiCachePut.value()) {
Cache cache = cacheManager.getCache(item.cacheName());
if (cache == null) {
continue;
}
// 解析缓存键
String key = multiCachePut.keyPrefix() + parser.parseExpression(item.key()).getValue(context, String.class);
if (item.ttl() > 0) {
// 如果有过期时间,使用缓存的put方法写入,部分缓存实现支持ttl,这里以RedisCache为例
cache.put(key, result);
// 如果是Redis缓存,可额外设置过期时间,这里简化为通用处理
} else {
cache.put(key, result);
}
}
return result;
}
}
配置缓存管理器
以Redis作为缓存实现为例,配置RedisCacheManager,确保缓存管理器能够正常管理缓存实例。如果使用其他缓存实现,只需要替换为对应的CacheManager即可。
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) {
// 默认缓存配置,过期时间1小时
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
// 针对不同的缓存名称配置不同的过期时间
Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
cacheConfigs.put("userInfoCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)));
cacheConfigs.put("userPermissionCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(2)));
return RedisCacheManager.builder(factory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigs)
.build();
}
}
使用示例
在业务方法上标注@MultiCachePut注解,配置需要写入的多个缓存,即可实现单次调用写入多缓存的效果。
import com.example.demo.annotation.MultiCachePut;
import org.springframework.stereotype.Service;
@Service
public class UserService {
// 更新用户信息后,同时更新用户基础信息缓存和用户权限缓存
@MultiCachePut(
value = {
@MultiCachePut.CacheItem(cacheName = "userInfoCache", key = "'user_' + #userId", ttl = 1800),
@MultiCachePut.CacheItem(cacheName = "userPermissionCache", key = "'permission_' + #userId", ttl = 7200)
},
keyPrefix = ""
)
public User updateUserInfo(Long userId, String userName, Integer age) {
// 模拟数据库更新操作
User user = new User(userId, userName, age);
// 更新数据库逻辑省略
return user;
}
// 测试用User类
static class User {
private Long id;
private String name;
private Integer age;
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
// getter和setter省略
}
}
注意事项
- 切面中需要确保目标方法执行成功后才写入缓存,如果方法抛出异常,不应该写入缓存,因此使用@Around注解在proceed()成功后再处理逻辑。
- SpEL表达式解析时需要注意变量的可用性,比如result变量只有在方法执行完成后才有值,因此缓存键如果使用result的属性,需要保证result不为null。
- 如果缓存实现不支持自定义过期时间,可以在切面中额外调用缓存的过期时间设置方法,或者统一在缓存管理器中配置不同缓存的默认过期时间。
- 如果需要支持删除多缓存的场景,可以类似地定义
@MultiCacheEvict注解,在切面中调用cache.evict()方法即可。
Spring_Cache缓存写入自定义缓存注解缓存管理器缓存同步修改时间:2026-06-28 13:03:38