在这种情况下如何配置WebClient代理

时间:2019-12-18 10:21:47

标签: java spring-webflux

我有很多代理主机,并且每个请求中都需要随机代理主机。

喜欢:

  • 请求1->代理是主机[X]
  • 请求2->代理是主机[X]
  • 请求3->代理是主机[X]

X0hosts.length()范围内是随机的

// proxy hosts
String[] hosts = {"ip1:port", "ip2:port", "ip3:port", ...}

@Bean("clientHttpConnector")
public ClientHttpConnector clientHttpConnector() {
    HttpClient httpClient = HttpClient.create()
            .tcpConfiguration(tcpClient ->
                    tcpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP).address(new InetSocketAddress("ip", port)))
            );
    return new ReactorClientHttpConnector(httpClient);
}

@Bean("webClient")
public WebClient webClient(@Qualifier("clientHttpConnector") ClientHttpConnector clientHttpConnector) {
    return WebClient.builder()
        .clientConnector(clientHttpConnector)
        .build();
}

用法:

@Component
@Slf4j
public class RestService {
    private final WebClient webclient;

    @Autowired
    public RestService(WebClient webclient) {
        this.webclient = webclient;
    }

    public void multiRequest() {
        // request 1.
        String resp1 = webclient.get().uri(uri1).retrieve().bodyToMono(String.class).block();

        // request 2.
        String resp2 = webclient.get().uri(uri2).retrieve().bodyToMono(String.class).block();

        // request 3.
        String resp3 = webclient.get().uri(uri3).retrieve().bodyToMono(String.class).block();
    }
}

那么,我该如何配置?

0 个答案:

没有答案