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

Spring 6 HTTP Interface方法如何通过@Cacheable实现缓存?

问题原因

你手动通过HttpServiceProxyFactory.createClient()创建的ExampleClient实例不在Spring容器管理范围内,Spring的缓存切面(由@EnableCaching启用)无法作用于非Spring管理的对象,因此@Cacheable注解不生效。

解决方案

方案1:使用官方推荐的@HttpServiceClient(Spring 6.1+/Spring Boot 3.2+)

这是Spring为HTTP Interface设计的声明式注册方式,自动将客户端纳入Spring容器管理,无需手动创建代理:

  1. 修改ExampleClient接口,用@HttpServiceClient替代类级别的@HttpExchange(参数可迁移到该注解中):
@HttpServiceClient(baseUrl = "/v1/example", accept = "application/json", contentType = "application/json")
public interface ExampleClient {

    @GetExchange(url = "/test")
    @Cacheable("example")
    ResponseEntity<ExampleClientResponse> test();
}
  1. 确保项目依赖Spring Boot 3.2+或Spring Framework 6.1+,并配置好WebClient Bean:
@Configuration
public class WebClientConfig {
    @Bean
    public WebClient webClient() {
        return WebClient.builder().baseUrl("http://your-api-host").build();
    }
}
  1. 在业务类中通过构造函数或@Autowired注入使用:
@Service
public class YourService {
    private final ExampleClient exampleClient;

    public YourService(ExampleClient exampleClient) {
        this.exampleClient = exampleClient;
    }

    // 调用exampleClient.test()时缓存会生效
}

方案2:将手动创建的代理纳入Spring容器管理

若无法升级Spring版本,可通过@Bean方法把ExampleClient注册为Spring Bean,让Spring为其应用缓存切面:

  1. 创建配置类定义ExampleClient Bean:
@Configuration
public class HttpClientConfig {

    @Bean
    public ExampleClient exampleClient(WebClient webClient) {
        return HttpServiceProxyFactory
                .builder(WebClientAdapter.forClient(webClient))
                .blockTimeout(Duration.ofSeconds(30))
                .build()
                .createClient(ExampleClient.class);
    }
}
  1. 同样通过构造函数或@Autowired注入使用ExampleClient,禁止手动创建实例。
验证要点
  • 确认主类上的@EnableCaching注解已正确添加,Spring会自动启用缓存切面。
  • 检查缓存管理器(如默认的ConcurrentMapCacheManager)是否正常工作,可通过日志或调试确认缓存的写入与读取逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 01:51:17