org.springframework.http.client.reactive.ReactorClientHttpConnector Java Examples

The following examples show how to use org.springframework.http.client.reactive.ReactorClientHttpConnector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClientTest.java    From influx-proxy with Apache License 2.0 8 votes vote down vote up
public static void main(String[] args) throws JsonProcessingException {
//        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.setSerializationInclusion(NON_NULL);
//        InfluxDB influxdb = InfluxDBFactory.connect("http://172.29.64.250:18086");
//        QueryResult result = influxdb.query(new Query("select * from health limit 1", "micrometerDb"));
//        System.out.println(objectMapper.writeValueAsString(result));
//        influxdb.close();

        TcpClient tcpClient = TcpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
        WebClient webClient = WebClient.builder()
                .baseUrl("http://localhost:8086")
                .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
                .filter(logRequest())
                .build();
        System.out.println(webClient.get().uri(uriBuilder -> uriBuilder
                .path("query")
                .queryParam("db", "micrometerDb")
                .queryParam("q", "select * from cpu")
                .build()
        )
                .exchange()
                .flatMap(clientResponse -> clientResponse.toEntity(String.class))
                .block().getBody());
    }
 
Example #2
Source File: CloudFoundryAcceptanceTest.java    From spring-cloud-app-broker with Apache License 2.0 6 votes vote down vote up
private WebClient getSslIgnoringWebClient() {
	return WebClient.builder()
		.clientConnector(new ReactorClientHttpConnector(HttpClient
			.create()
			.secure(t -> {
				try {
					t.sslContext(SslContextBuilder
						.forClient()
						.trustManager(InsecureTrustManagerFactory.INSTANCE)
						.build());
				}
				catch (SSLException e) {
					if (LOG.isDebugEnabled()) {
						LOG.debug("problem ignoring SSL in WebClient", e);
					}
				}
			})))
		.build();
}
 
Example #3
Source File: TimeoutLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
private ReactorClientHttpConnector getConnector() throws SSLException {
    SslContext sslContext = SslContextBuilder
            .forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();

    TcpClient tcpClient = TcpClient
      .create()
      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_MILLIS)
      .doOnConnected(connection -> {
          connection.addHandlerLast(new ReadTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
          connection.addHandlerLast(new WriteTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
      });

    HttpClient httpClient = HttpClient.from(tcpClient).secure(t -> t.sslContext(sslContext));
    return new ReactorClientHttpConnector(httpClient);
}
 
Example #4
Source File: WebClientLoggingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenNettyHttpClientWithCustomLogger_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() {

    reactor.netty.http.client.HttpClient httpClient = HttpClient
      .create()
      .tcpConfiguration(
        tc -> tc.bootstrap(
          b -> BootstrapHandlers.updateLogSupport(b, new CustomLogger(HttpClient.class))));
    WebClient
      .builder()
      .clientConnector(new ReactorClientHttpConnector(httpClient))
      .build()
      .post()
      .uri(sampleUrl)
      .body(BodyInserters.fromObject(post))
      .exchange()
      .block();

    verify(nettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleResponseBody)));
}
 
Example #5
Source File: WebClientLoggingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenNettyHttpClientWithWiretap_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() {

    reactor.netty.http.client.HttpClient httpClient = HttpClient
      .create()
      .wiretap(true);
    WebClient
      .builder()
      .clientConnector(new ReactorClientHttpConnector(httpClient))
      .build()
      .post()
      .uri(sampleUrl)
      .body(BodyInserters.fromObject(post))
      .exchange()
      .block();

    verify(nettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains("00000300")));
}
 
Example #6
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
static ClientHttpConnector usingReactorNetty(ClientOptions options, SslConfiguration sslConfiguration) {
	HttpClient client = HttpClient.create();

	if (hasSslConfiguration(sslConfiguration)) {

		SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
		configureSsl(sslConfiguration, sslContextBuilder);

		client = client.secure(builder -> {
			builder.sslContext(sslContextBuilder);
		});
	}

	client = client.tcpConfiguration(it -> it.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
			Math.toIntExact(options.getConnectionTimeout().toMillis())));

	return new ReactorClientHttpConnector(client);
}
 
Example #7
Source File: InstanceWebClient.java    From Moss with Apache License 2.0 6 votes vote down vote up
private static WebClient.Builder createDefaultWebClient(Duration connectTimeout, Duration readTimeout) {
    HttpClient httpClient = HttpClient.create()
                                      .compress(true)
                                      .tcpConfiguration(tcp -> tcp.bootstrap(bootstrap -> bootstrap.option(
                                          ChannelOption.CONNECT_TIMEOUT_MILLIS,
                                          (int) connectTimeout.toMillis()
                                      )).observe((connection, newState) -> {
                                          if (ConnectionObserver.State.CONNECTED.equals(newState)) {
                                              connection.addHandlerLast(new ReadTimeoutHandler(readTimeout.toMillis(),
                                                  TimeUnit.MILLISECONDS
                                              ));
                                          }
                                      }));
    ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
    return WebClient.builder().clientConnector(connector);
}
 
Example #8
Source File: BackendService.java    From influx-proxy with Apache License 2.0 5 votes vote down vote up
public WebClient getWebClientFromCacheOrCreate(BackendNode node) {
    WebClient client = webClientCache.get(node.getUrl());
    if (client != null) {
        return client;
    }
    synchronized (webClientCache) {
        client = webClientCache.get(node.getUrl());
        if (client != null) {
            return client;
        }
        int queryTimeout=Optional.ofNullable(node.getQueryTimeout()).orElse(DEFAULT_QUERY_TIMEOUT);
        int writeTimeout=Optional.ofNullable(node.getWriteTimeout()).orElse(DEFAULT_WRITE_TIMEOUT);
        int timeout=Math.max(queryTimeout,writeTimeout);

        TcpClient tcpClient = TcpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout)
                .doOnConnected(conn -> conn
                        .addHandlerLast(new ReadTimeoutHandler(timeout))
                        .addHandlerLast(new WriteTimeoutHandler(timeout)));
        WebClient webClient = WebClient.builder()
                .baseUrl(node.getUrl())
                .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient).keepAlive(false)))
                .filter(logRequest())
                .build();
        webClientCache.put(node.getUrl(), webClient);
        return webClient;
    }
}
 
Example #9
Source File: WebClientBraveTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
/**
 * Normally, the HTTP connector would be statically initialized. This ensures the
 * {@link HttpClient} is configured for the mock endpoint.
 */
@Bean
@Order(0)
public WebClientCustomizer clientConnectorCustomizer(HttpClient httpClient,
		URI baseUrl) {
	return (builder) -> builder.baseUrl(baseUrl.toString())
			.clientConnector(new ReactorClientHttpConnector(httpClient));
}
 
Example #10
Source File: ModifyRequestBodyGatewayFilterFactorySslTimeoutTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	try {
		SslContext sslContext = SslContextBuilder.forClient()
				.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
		HttpClient httpClient = HttpClient.create()
				.secure(ssl -> ssl.sslContext(sslContext));
		setup(new ReactorClientHttpConnector(httpClient),
				"https://localhost:" + port);
	}
	catch (SSLException e) {
		throw new RuntimeException(e);
	}
}
 
Example #11
Source File: SingleCertSSLTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	try {
		SslContext sslContext = SslContextBuilder.forClient()
				.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
		HttpClient httpClient = HttpClient.create()
				.secure(ssl -> ssl.sslContext(sslContext));
		setup(new ReactorClientHttpConnector(httpClient),
				"https://localhost:" + port);
	}
	catch (SSLException e) {
		throw new RuntimeException(e);
	}
}
 
Example #12
Source File: ReactorClientHttpConnectorCreator.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpConnector createConnector(TimeoutConfiguration configuration) {
    return new ReactorClientHttpConnector(httpClient.tcpConfiguration(client ->
            client.option(CONNECT_TIMEOUT_MILLIS, toMillis(configuration.getConnection()))
                    .doOnConnected(connection -> connection
                            .addHandlerLast(new ReadTimeoutHandler(configuration.getRead().toMillis(), MILLISECONDS))
                            .addHandlerLast(new WriteTimeoutHandler(configuration.getWrite().toMillis(), MILLISECONDS)))));
}
 
Example #13
Source File: SseIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Parameterized.Parameters(name = "server [{0}] webClient [{1}]")
public static Object[][] arguments() {
	File base = new File(System.getProperty("java.io.tmpdir"));
	return new Object[][] {
			{new JettyHttpServer(), new ReactorClientHttpConnector()},
			{new JettyHttpServer(), new JettyClientHttpConnector()},
			{new ReactorHttpServer(), new ReactorClientHttpConnector()},
			{new ReactorHttpServer(), new JettyClientHttpConnector()},
			{new TomcatHttpServer(base.getAbsolutePath()), new ReactorClientHttpConnector()},
			{new TomcatHttpServer(base.getAbsolutePath()), new JettyClientHttpConnector()},
			{new UndertowHttpServer(), new ReactorClientHttpConnector()},
			{new UndertowHttpServer(), new JettyClientHttpConnector()}
	};
}
 
Example #14
Source File: TitusWebClientAddOns.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static WebClient.Builder addTitusDefaults(WebClient.Builder clientBuilder,
                                                 HttpClient httpClient,
                                                 WebClientMetric webClientMetric) {
    HttpClient updatedHttpClient = addMetricCallbacks(
            addLoggingCallbacks(httpClient),
            webClientMetric
    );

    return clientBuilder.clientConnector(new ReactorClientHttpConnector(updatedHttpClient));
}
 
Example #15
Source File: WebClientDataBufferAllocatingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private ReactorClientHttpConnector initConnector() {
	if (bufferFactory instanceof NettyDataBufferFactory) {
		ByteBufAllocator allocator = ((NettyDataBufferFactory) bufferFactory).getByteBufAllocator();
		return new ReactorClientHttpConnector(this.factory, httpClient ->
				httpClient.tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.ALLOCATOR, allocator)));
	}
	else {
		return new ReactorClientHttpConnector();
	}
}
 
Example #16
Source File: ClientHttpConnectorFactory.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ClientHttpConnector} for the given {@link ClientOptions}.
 * @param options must not be {@literal null}
 * @return a new {@link ClientHttpConnector}.
 */
public static ClientHttpConnector create(ClientOptions options) {
	HttpClient httpClient = HttpClient.create();

	if (usingCustomCerts(options)) {
		TrustManagerFactory trustManagerFactory = sslCertificateUtils
				.createTrustManagerFactory(options.getCaCertFiles());

		httpClient = httpClient.secure((sslContextSpec) -> sslContextSpec.sslContext(
				SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustManagerFactory)));
	}
	else {
		httpClient = httpClient.secure((sslContextSpec) -> {
			try {
				sslContextSpec.sslContext(new JdkSslContext(SSLContext.getDefault(), true, null,
						IdentityCipherSuiteFilter.INSTANCE, null, ClientAuth.REQUIRE, null, false));
			}
			catch (NoSuchAlgorithmException ex) {
				logger.error("Error configuring HTTP connections", ex);
				throw new RuntimeException("Error configuring HTTP connections", ex);
			}
		});
	}

	if (options.getConnectionTimeout() != null) {
		httpClient = httpClient
				.tcpConfiguration((tcpClient) -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
						Math.toIntExact(options.getConnectionTimeout().toMillis())));
	}

	return new ReactorClientHttpConnector(httpClient);
}
 
Example #17
Source File: DemoClient.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
public static final void main(String[] args) throws IOException {
        WebClient client = WebClient.builder()
                //see: https://github.com/jetty-project/jetty-reactive-httpclient
                //.clientConnector(new JettyClientHttpConnector())
                .clientConnector(new ReactorClientHttpConnector())
                .codecs(
                        clientCodecConfigurer ->{
                            // use defaultCodecs() to apply DefaultCodecs
                            // clientCodecConfigurer.defaultCodecs();

                            // alter a registered encoder/decoder based on the default config.
                            // clientCodecConfigurer.defaultCodecs().jackson2Encoder(...)

                            // Or
                            // use customCodecs to register Codecs from scratch.
                            clientCodecConfigurer.customCodecs().register(new Jackson2JsonDecoder());
                            clientCodecConfigurer.customCodecs().register(new Jackson2JsonEncoder());
                        }

                )
                .exchangeStrategies(ExchangeStrategies.withDefaults())
//                .exchangeFunction(ExchangeFunctions.create(new ReactorClientHttpConnector())
//                        .filter(ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {})))
//                .filter(ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {clientRequest.}))
                //.defaultHeaders(httpHeaders -> httpHeaders.addAll())
                .baseUrl("http://localhost:8080")
                .build();
        client
            .get()
            .uri("/posts")
            .exchange()
            .flatMapMany(res -> res.bodyToFlux(Post.class))
            .log()
            .subscribe(post -> System.out.println("post: " + post));

        System.out.println("Client is started!");
        System.in.read();
    }
 
Example #18
Source File: WebClientIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Parameterized.Parameters(name = "webClient [{0}]")
public static Object[][] arguments() {
	return new Object[][] {
			{new JettyClientHttpConnector()},
			{new ReactorClientHttpConnector()}
	};
}
 
Example #19
Source File: DefaultWebClientBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private ExchangeFunction initExchangeFunction() {
	if (this.exchangeFunction != null) {
		return this.exchangeFunction;
	}
	else if (this.connector != null) {
		return ExchangeFunctions.create(this.connector, this.exchangeStrategies);
	}
	else {
		return ExchangeFunctions.create(new ReactorClientHttpConnector(), this.exchangeStrategies);
	}
}
 
Example #20
Source File: HttpClientPluginConfiguration.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Web client plugin soul plugin.
 *
 * @param httpClient the http client
 * @return the soul plugin
 */
@Bean
public SoulPlugin webClientPlugin(final ObjectProvider<HttpClient> httpClient) {
    WebClient webClient = WebClient.builder()
            .clientConnector(new ReactorClientHttpConnector(Objects.requireNonNull(httpClient.getIfAvailable())))
            .build();
    return new WebClientPlugin(webClient);
}
 
Example #21
Source File: GreetingLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private ReactorClientHttpConnector getConnector() throws SSLException {
    SslContext sslContext = SslContextBuilder
            .forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();
    HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext));
    return new ReactorClientHttpConnector(httpClient);
}
 
Example #22
Source File: SseIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Parameterized.Parameters(name = "server [{0}] webClient [{1}]")
public static Object[][] arguments() {
	File base = new File(System.getProperty("java.io.tmpdir"));
	return new Object[][] {
			{new JettyHttpServer(), new ReactorClientHttpConnector()},
			{new JettyHttpServer(), new JettyClientHttpConnector()},
			{new ReactorHttpServer(), new ReactorClientHttpConnector()},
			{new ReactorHttpServer(), new JettyClientHttpConnector()},
			{new TomcatHttpServer(base.getAbsolutePath()), new ReactorClientHttpConnector()},
			{new TomcatHttpServer(base.getAbsolutePath()), new JettyClientHttpConnector()},
			{new UndertowHttpServer(), new ReactorClientHttpConnector()},
			{new UndertowHttpServer(), new JettyClientHttpConnector()}
	};
}
 
Example #23
Source File: WebClientDataBufferAllocatingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ReactorClientHttpConnector initConnector() {
	if (bufferFactory instanceof NettyDataBufferFactory) {
		ByteBufAllocator allocator = ((NettyDataBufferFactory) bufferFactory).getByteBufAllocator();
		return new ReactorClientHttpConnector(this.factory, httpClient ->
				httpClient.tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.ALLOCATOR, allocator)));
	}
	else {
		return new ReactorClientHttpConnector();
	}
}
 
Example #24
Source File: WebClientIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Parameterized.Parameters(name = "webClient [{0}]")
public static Object[][] arguments() {
	return new Object[][] {
			{new JettyClientHttpConnector()},
			{new ReactorClientHttpConnector()}
	};
}
 
Example #25
Source File: DefaultWebClientBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ExchangeFunction initExchangeFunction() {
	if (this.exchangeFunction != null) {
		return this.exchangeFunction;
	}
	else if (this.connector != null) {
		return ExchangeFunctions.create(this.connector, this.exchangeStrategies);
	}
	else {
		return ExchangeFunctions.create(new ReactorClientHttpConnector(), this.exchangeStrategies);
	}
}
 
Example #26
Source File: WebClientConfig.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "cf.sslValidationSkipped", havingValue="true")
public WebClient insecureWebClient(WebClient.Builder builder) throws SSLException {
    SslContext sslContext =
        SslContextBuilder
            .forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();
    TcpClient tcpClient = TcpClient.create().secure(sslProviderBuilder -> sslProviderBuilder.sslContext(sslContext));
    HttpClient httpClient = HttpClient.from(tcpClient);
    return builder
            .clientConnector(new ReactorClientHttpConnector(httpClient))
            .build();
}
 
Example #27
Source File: DefaultWebTestClientBuilder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/** Connect to server via Reactor Netty. */
DefaultWebTestClientBuilder() {
	this(new ReactorClientHttpConnector());
}
 
Example #28
Source File: QueryIndexEndpointStrategyTest.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
private ReactorClientHttpConnector httpConnector() {
	SslContextBuilder sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE);
	HttpClient client = HttpClient.create().secure((ssl) -> ssl.sslContext(sslCtx));
	return new ReactorClientHttpConnector(client);
}
 
Example #29
Source File: TLSRouteProviderTest.java    From syncope with Apache License 2.0 4 votes vote down vote up
private WebTestClient webClient(final SslContext sslContext) throws SSLException {
    HttpClient httpClient = HttpClient.create().
            secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
    ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
    return WebTestClient.bindToServer(connector).baseUrl("https://localhost:" + sraPort).build();
}
 
Example #30
Source File: BaseWebClientTests.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
	setup(new ReactorClientHttpConnector(), "http://localhost:" + port);
}