SpringBoot3.2 + spring6.1 声明式HTTP客户端

452 阅读1分钟

spring6.1之后, 配置声明式客户端发生了变化, 原来的HttpServiceProxyFactory.build方法已弃用

image.png 采用新的HttpServiceProxyFactory.builderFor方法

image.png

WebClientAdapter.forClient也已弃用

image.png 采用新的WebClientAdapter.create方法

更新后的配置示例:

@Bean
DeomClient initWebClient() {
  WebClient client = WebClient.builder().baseUrl("http://localhost:8080/").build();
  HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(WebClientAdapter.create(client)).build();
  return factory.createClient(DeomClient.class);
}

请求客户端示例:

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@HttpExchange()
public interface DeomClient {

  @GetExchange("/test")
  Flux<Object> getAll();

  @PostExchange("/test2")
  Mono<Boolean> save(@RequestBody Object object);

}

使用示例:

@Autowired 
private DeomClient deomClient; 

public void test() {

    deomClient.getAll().subscribe(data -> log.info(data));
    
}