如何为WebClient设置基本URL和查询参数?

问题描述 投票:0回答:1

在我的服务中,我必须从带有参数的一些不同的URL中获得响应。

  1. http://a.com:8080/path1?param1=v1获取
  2. http://b.com:8080/path2?param2=v2获取
  3. http://c.com:8080/path3?param3=v3获取

我正在使用WebClient进行以下工作。

public class WebClientTest {
    private WebClient webClient = WebClient.builder().build();

    @Test
    public void webClientTest() {
        Mono<String> a = webClient.get()
            .uri(uriBuilder -> uriBuilder.scheme("http").host("a.com").port(8080).path("/path1")
                    .queryParam("param1", "v1")
                    .build())
            .retrieve()
            .bodyToMono(String.class);

        Mono<String> b = webClient.get()
            .uri(uriBuilder -> uriBuilder.scheme("http").host("b.com").port(8080).path("/path2")
                    .queryParam("param2", "v2")
                    .build())
            .retrieve()
            .bodyToMono(String.class);

        Mono<String> c = webClient.get()
            .uri(uriBuilder -> uriBuilder.scheme("http").host("c.com").port(8080).path("/path3")
                    .queryParam("param3", "v3")
                    .build())
            .retrieve()
            .bodyToMono(String.class);

        //zip the result
    }
}

如您所见,我必须一次又一次地设置方案,主机,端口。所以我的问题是:1.我是否以正确的方式使用WebClient?2.是否可以在一个方法中一起设置方案,主机,端口?我知道webClient.get().uri("http://a.com:8080/path1?param1=v1").retrieve()有效,但是我期望的是:

    webClient.get()
            .uri(uriBuilder -> uriBuilder/*.url("http://a.com:8080/path1")*/
                    .queryParam("param1", "v1")
                    .build())
            .retrieve()
            .bodyToMono(String.class);
spring webclient query-parameters
1个回答
0
投票

我解决此问题的方法是为每个不同的URL都拥有一个WebClient。

所以您会有

   private WebClient aClient = WebClient.create("a.com")
   private WebClient bClient = WebClient.create("b.com")
   private WebClient cClient = WebClient.create("c.com")

然后根据您的呼叫与每个WebClient进行交互。

https://docs.spring.io/spring/docs/5.0.7.RELEASE/spring-framework-reference/web-reactive.html#webflux-client-retrieve

© www.soinside.com 2019 - 2024. All rights reserved.