如何用Spring Cache实现单次调用写入多个缓存

来源:网站建设作者:南京GEO公司头衔:草根站长
导读:本期聚焦于小伙伴创作的《如何用Spring Cache实现单次调用写入多个缓存》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《如何用Spring Cache实现单次调用写入多个缓存》有用,将其分享出去将是对创作者最好的鼓励。

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

如何用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

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。