You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot缓存未生效求助:重复URL仍调用接口

Spring Boot缓存不生效的问题分析与解决

核心原因

Spring的缓存注解(如@Cacheable)基于AOP代理实现,私有方法无法被Spring的代理机制拦截,导致注解完全不触发缓存逻辑,每次都会执行方法体代码。

解决方案

  1. 修改方法访问权限为public
    将postMessageToGateway方法的权限从private改为public,确保Spring能够代理该方法,从而触发缓存逻辑:

    @Cacheable("bcaType")
    public String postMessageToGateway(String url) throws MalformedURLException {
        // 原有逻辑保持不变
        SrpInvokerImpl srpInvokerImpl = new SrpInvokerImpl();
        MsgGetBcaTypeCriteriaNewMsgBuilder msgGetBcaTypeCriteriaNewMsgBuilder = new MsgGetBcaTypeCriteriaNewMsgBuilder();
    
        return srpInvokerImpl.postMessageToGateway(msgGetBcaTypeCriteriaNewMsgBuilder.prepareMessage(),
                new URL(url));
    }
    
  2. 避免类内部直接调用(若存在)
    如果是在MsgBcaTypeCategory类的其他方法中通过this.postMessageToGateway(url)直接调用,会绕开代理导致缓存失效。此时需要通过Spring容器获取当前Bean的代理对象调用,示例如下:

    @Autowired
    private MsgBcaTypeCategory selfProxy; // 注入自身代理对象
    
    public void someOtherMethod(String url) throws MalformedURLException {
        selfProxy.postMessageToGateway(url); // 通过代理对象触发缓存
    }
    

    或者将该缓存方法抽取到独立的Spring Bean中,通过依赖注入调用。

额外检查点

  • 建议将@EnableCaching注解放在Spring配置类(如主启动类或标注@Configuration的类)上,当前放在SimpleCacheCustomizer上虽可能生效,但配置类上添加更规范,避免潜在问题。
  • 你的CacheManager配置中已正确指定缓存名称bcaType,这部分无需修改。

内容的提问来源于stack exchange,提问作者ritul sinha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:02:07