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容器管理,无需手动创建代理:
- 修改
ExampleClient接口,用@HttpServiceClient替代类级别的@HttpExchange(参数可迁移到该注解中):
@HttpServiceClient(baseUrl = "/v1/example", accept = "application/json", contentType = "application/json") public interface ExampleClient { @GetExchange(url = "/test") @Cacheable("example") ResponseEntity<ExampleClientResponse> test(); }
- 确保项目依赖Spring Boot 3.2+或Spring Framework 6.1+,并配置好
WebClientBean:
@Configuration public class WebClientConfig { @Bean public WebClient webClient() { return WebClient.builder().baseUrl("http://your-api-host").build(); } }
- 在业务类中通过构造函数或
@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为其应用缓存切面:
- 创建配置类定义
ExampleClientBean:
@Configuration public class HttpClientConfig { @Bean public ExampleClient exampleClient(WebClient webClient) { return HttpServiceProxyFactory .builder(WebClientAdapter.forClient(webClient)) .blockTimeout(Duration.ofSeconds(30)) .build() .createClient(ExampleClient.class); } }
- 同样通过构造函数或
@Autowired注入使用ExampleClient,禁止手动创建实例。
验证要点
- 确认主类上的
@EnableCaching注解已正确添加,Spring会自动启用缓存切面。 - 检查缓存管理器(如默认的
ConcurrentMapCacheManager)是否正常工作,可通过日志或调试确认缓存的写入与读取逻辑。
内容的提问来源于stack exchange,提问作者Toniotti
相关产品推荐
相关产品推荐

