reactor.netty.tcp.TcpClient Java Examples
The following examples show how to use
reactor.netty.tcp.TcpClient.
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 |
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: TcpSslUriHandler.java From alibaba-rsocket-broker with Apache License 2.0 | 6 votes |
@Override public Optional<ClientTransport> buildClient(URI uri) { Objects.requireNonNull(uri, "uri must not be null"); if (!SCHEME.equals(uri.getScheme())) { return Optional.empty(); } try { SslContext context = SslContextBuilder .forClient() .protocols(protocols) .sslProvider(getSslProvider()) .trustManager(trustManagerFactory).build(); TcpClient tcpClient = TcpClient.create() .host(uri.getHost()) .port(uri.getPort()) .secure(ssl -> ssl.sslContext(context)); return Optional.of(TcpClientTransport.create(tcpClient)); } catch (Exception e) { return Optional.empty(); } }
Example #3
Source File: TimeoutLiveTest.java From tutorials with MIT License | 6 votes |
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: DemoApplication.java From spring-boot-rsocket with Apache License 2.0 | 6 votes |
public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); RSocket rSocket = RSocketFactory.connect() .transport(WebsocketClientTransport.create( HttpClient.from(TcpClient.create() .host("localhost") .port(8080)), "/rsocket" )) .start() .block(); logger.info( rSocket.requestResponse(DefaultPayload.create("HelloWorld")) .map(Payload::getDataUtf8) .block() ); }
Example #5
Source File: DemoApplication.java From spring-boot-rsocket with Apache License 2.0 | 6 votes |
public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); RSocket rSocket = RSocketFactory.connect() .transport(WebsocketClientTransport.create( HttpClient.from(TcpClient.create() .host("localhost") .port(8080)), "/rsocket-rpc" )) .start() .block(); GreeterClient client = new GreeterClient(rSocket); client.streamGreet(HelloRequest.newBuilder().setName("Jon Doe").build()) .log() .blockLast(); client.requestGreet(HelloRequest.newBuilder().setName("Arthur Conan Doyle").build()) .log() .block(); }
Example #6
Source File: DiscardClient.java From reactor-netty with Apache License 2.0 | 6 votes |
public static void main(String[] args) { TcpClient client = TcpClient.create() .port(PORT) .wiretap(WIRETAP); if (SECURE) { client = client.secure( spec -> spec.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE))); } Connection connection = client.handle((in, out) -> { // Discards the incoming data and releases the buffers in.receive().subscribe(); return out.sendString(Flux.interval(Duration.ofMillis(100)) .map(l -> l + "")); }) .connectNow(); connection.onDispose() .block(); }
Example #7
Source File: EchoClient.java From reactor-netty with Apache License 2.0 | 6 votes |
public static void main(String[] args) { TcpClient client = TcpClient.create() .port(PORT) .wiretap(WIRETAP); if (SECURE) { client = client.secure( spec -> spec.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE))); } Connection connection = client.handle((in, out) -> out.send(Flux.concat(ByteBufFlux.fromString(Mono.just("echo")), in.receive().retain()))) .connectNow(); connection.onDispose() .block(); }
Example #8
Source File: HttpServerTests.java From reactor-netty with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("deprecation") public void testTcpConfiguration_2() throws Exception { CountDownLatch latch = new CountDownLatch(10); LoopResources loop = LoopResources.create("testTcpConfiguration"); ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); doTestTcpConfiguration( HttpServer.from(configureTcpServer(TcpServer.create(), loop, group, latch)), HttpClient.from(configureTcpClient(TcpClient.create(), loop, group, latch)) ); assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); FutureMono.from(group.close()) .then(loop.disposeLater()) .block(Duration.ofSeconds(30)); }
Example #9
Source File: ReactorNettyTcpClient.java From java-technology-stack with MIT License | 5 votes |
/** * Constructor with an externally created {@link TcpClient} instance whose * lifecycle is expected to be managed externally. * @param tcpClient the TcpClient instance to use * @param codec for encoding and decoding the input/output byte streams * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec */ public ReactorNettyTcpClient(TcpClient tcpClient, ReactorNettyCodec<P> codec) { Assert.notNull(tcpClient, "TcpClient is required"); Assert.notNull(codec, "ReactorNettyCodec is required"); this.tcpClient = tcpClient; this.codec = codec; this.channelGroup = null; this.loopResources = null; this.poolResources = null; }
Example #10
Source File: HttpServerTests.java From reactor-netty with Apache License 2.0 | 5 votes |
private void doTestDecodingFailureLastHttpContent(String message, String... expectations) throws Exception { TcpClient tcpClient = TcpClient.create() .port(disposableServer.port()) .wiretap(true); Connection connection = tcpClient.connectNow(); CountDownLatch latch = new CountDownLatch(1); connection.channel() .closeFuture() .addListener(f -> latch.countDown()); AtomicReference<String> result = new AtomicReference<>(); connection.inbound() .receive() .asString() .doOnNext(result::set) .subscribe(); connection.outbound() .sendString(Mono.just(message)) .then() .subscribe(); assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); assertThat(result.get()).contains(expectations); assertThat(connection.channel().isActive()).isFalse(); }
Example #11
Source File: Client.java From r2dbc-mysql with Apache License 2.0 | 5 votes |
static Mono<Client> connect(SocketAddress address, MySqlSslConfiguration ssl, ConnectionContext context, @Nullable Duration connectTimeout) { requireNonNull(address, "address must not be null"); requireNonNull(ssl, "ssl must not be null"); requireNonNull(context, "context must not be null"); TcpClient tcpClient = TcpClient.newConnection(); if (connectTimeout != null) { tcpClient = tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.toMillis())); } return tcpClient.remoteAddress(() -> address).connect() .map(conn -> new ReactorNettyClient(conn, ssl, context)); }
Example #12
Source File: WebClientConfig.java From cf-butler with Apache License 2.0 | 5 votes |
@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 #13
Source File: Client.java From r2dbc-mysql with Apache License 2.0 | 5 votes |
static Mono<Client> connect(SocketAddress address, MySqlSslConfiguration ssl, ConnectionContext context, @Nullable Duration connectTimeout) { requireNonNull(address, "address must not be null"); requireNonNull(ssl, "ssl must not be null"); requireNonNull(context, "context must not be null"); TcpClient tcpClient = TcpClient.newConnection(); if (connectTimeout != null) { tcpClient = tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.toMillis())); } return tcpClient.remoteAddress(() -> address).connect() .map(conn -> new ReactorNettyClient(conn, ssl, context)); }
Example #14
Source File: StatsdMeterRegistry.java From micrometer with Apache License 2.0 | 5 votes |
private void prepareTcpClient(Publisher<String> publisher) { AtomicReference<TcpClient> tcpClientReference = new AtomicReference<>(); TcpClient tcpClient = TcpClient.create() .host(statsdConfig.host()) .port(statsdConfig.port()) .handle((in, out) -> out .sendString(publisher) .neverComplete()) .doOnDisconnected(connection -> connectAndSubscribe(tcpClientReference.get())); tcpClientReference.set(tcpClient); connectAndSubscribe(tcpClient); }
Example #15
Source File: StatsdMeterRegistry.java From micrometer with Apache License 2.0 | 5 votes |
private void connectAndSubscribe(TcpClient tcpClient) { retryReplaceClient(Mono.defer(() -> { if (started.get()) { return tcpClient.connect(); } return Mono.empty(); })); }
Example #16
Source File: DefaultEsWebClientFactory.java From titus-control-plane with Apache License 2.0 | 5 votes |
private HttpClient buildHttpClient() { return HttpClient.create().tcpConfiguration(tcpClient -> { TcpClient tcpClientWithConnectionTimeout = tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, esClientConfiguration.getConnectTimeoutMillis()); return tcpClientWithConnectionTimeout.doOnConnected(connection -> { //TODO Investigate why WriteTimeoutHandler appears to be broken in netty-handler 4.1.36.RELEASE package. connection.addHandlerLast(new ReadTimeoutHandler(esClientConfiguration.getReadTimeoutSeconds())); }); }); }
Example #17
Source File: ReactorNettyTcpClient.java From java-technology-stack with MIT License | 5 votes |
/** * A variant of {@link #ReactorNettyTcpClient(String, int, ReactorNettyCodec)} * that still manages the lifecycle of the {@link TcpClient} and underlying * resources, but allows for direct configuration of other properties of the * client through a {@code Function<TcpClient, TcpClient>}. * @param clientConfigurer the configurer function * @param codec for encoding and decoding the input/output byte streams * @since 5.1.3 * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec */ public ReactorNettyTcpClient(Function<TcpClient, TcpClient> clientConfigurer, ReactorNettyCodec<P> codec) { Assert.notNull(codec, "ReactorNettyCodec is required"); this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); this.loopResources = LoopResources.create("tcp-client-loop"); this.poolResources = ConnectionProvider.elastic("tcp-client-pool"); this.codec = codec; this.tcpClient = clientConfigurer.apply(TcpClient .create(this.poolResources) .runOn(this.loopResources, false) .doOnConnected(conn -> this.channelGroup.add(conn.channel()))); }
Example #18
Source File: ReactorNettyTcpClient.java From spring-analysis-note with MIT License | 5 votes |
/** * A variant of {@link #ReactorNettyTcpClient(String, int, ReactorNettyCodec)} * that still manages the lifecycle of the {@link TcpClient} and underlying * resources, but allows for direct configuration of other properties of the * client through a {@code Function<TcpClient, TcpClient>}. * @param clientConfigurer the configurer function * @param codec for encoding and decoding the input/output byte streams * @since 5.1.3 * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec */ public ReactorNettyTcpClient(Function<TcpClient, TcpClient> clientConfigurer, ReactorNettyCodec<P> codec) { Assert.notNull(codec, "ReactorNettyCodec is required"); this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); this.loopResources = LoopResources.create("tcp-client-loop"); this.poolResources = ConnectionProvider.elastic("tcp-client-pool"); this.codec = codec; this.tcpClient = clientConfigurer.apply(TcpClient .create(this.poolResources) .runOn(this.loopResources, false) .doOnConnected(conn -> this.channelGroup.add(conn.channel()))); }
Example #19
Source File: HttpServerTests.java From reactor-netty with Apache License 2.0 | 5 votes |
@Test public void testIssue825() throws Exception { disposableServer = HttpServer.create() .port(0) .handle((req, resp) -> resp.sendString(Mono.just("test"))) .wiretap(true) .bindNow(); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); CountDownLatch latch = new CountDownLatch(1); Connection client = TcpClient.create() .port(disposableServer.port()) .handle((in, out) -> { in.withConnection(x -> x.addHandlerFirst(new HttpClientCodec())) .receiveObject() .ofType(DefaultHttpContent.class) .as(ByteBufFlux::fromInbound) // ReferenceCounted::release is deliberately invoked // so that .release() in FluxReceive.drainReceiver will fail .subscribe(ReferenceCounted::release, t -> latch.countDown(), null); return out.sendObject(Flux.just(request)) .neverComplete(); }) .wiretap(true) .connectNow(); assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); client.disposeNow(); }
Example #20
Source File: HttpServerTests.java From reactor-netty with Apache License 2.0 | 5 votes |
private void doTest(int port, String message) throws Exception { TcpClient tcpClient = TcpClient.create() .port(port) .wiretap(true); Connection connection = tcpClient.connectNow(); CountDownLatch latch = new CountDownLatch(2); connection.channel() .closeFuture() .addListener(f -> latch.countDown()); AtomicReference<String> result = new AtomicReference<>(); connection.inbound() .receive() .asString() .doOnNext(s -> { result.set(s); latch.countDown(); }) .subscribe(); connection.outbound() .sendString(Mono.just(message)) .then() .subscribe(); assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); assertThat(result.get()).contains("test", "connection: close"); assertThat(connection.channel().isActive()).isFalse(); }
Example #21
Source File: ReactorNettyTcpClient.java From spring-analysis-note with MIT License | 5 votes |
/** * Simple constructor with the host and port to use to connect to. * <p>This constructor manages the lifecycle of the {@link TcpClient} and * underlying resources such as {@link ConnectionProvider}, * {@link LoopResources}, and {@link ChannelGroup}. * <p>For full control over the initialization and lifecycle of the * TcpClient, use {@link #ReactorNettyTcpClient(TcpClient, ReactorNettyCodec)}. * @param host the host to connect to * @param port the port to connect to * @param codec for encoding and decoding the input/output byte streams * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec */ public ReactorNettyTcpClient(String host, int port, ReactorNettyCodec<P> codec) { Assert.notNull(host, "host is required"); Assert.notNull(codec, "ReactorNettyCodec is required"); this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); this.loopResources = LoopResources.create("tcp-client-loop"); this.poolResources = ConnectionProvider.elastic("tcp-client-pool"); this.codec = codec; this.tcpClient = TcpClient.create(this.poolResources) .host(host).port(port) .runOn(this.loopResources, false) .doOnConnected(conn -> this.channelGroup.add(conn.channel())); }
Example #22
Source File: HttpServerTests.java From reactor-netty with Apache License 2.0 | 5 votes |
private TcpClient configureTcpClient(TcpClient tcp, LoopResources loop, ChannelGroup group, CountDownLatch latch) { return tcp.wiretap(true) .runOn(loop) .channelGroup(group) .doOnConnected(c -> latch.countDown()) .doOnDisconnected(c -> latch.countDown()) .noSSL() .noProxy() .remoteAddress(() -> disposableServer.address()) .attr(AttributeKey.valueOf("testTcpConfiguration"), "testTcpConfiguration") .option(ChannelOption.valueOf("testTcpConfiguration"), "testTcpConfiguration") .observe((conn, state) -> latch.countDown()) .doOnChannelInit((observer, channel, address) -> latch.countDown()); }
Example #23
Source File: WebsocketClientTransport.java From rsocket-java with Apache License 2.0 | 5 votes |
/** * Creates a new instance * * @param uri the URI to connect to * @return a new instance * @throws NullPointerException if {@code uri} is {@code null} */ public static WebsocketClientTransport create(URI uri) { Objects.requireNonNull(uri, "uri must not be null"); boolean isSecure = uri.getScheme().equals("wss") || uri.getScheme().equals("https"); TcpClient client = (isSecure ? TcpClient.create().secure() : TcpClient.create()) .host(uri.getHost()) .port(uri.getPort() == -1 ? (isSecure ? 443 : 80) : uri.getPort()); return new WebsocketClientTransport(HttpClient.from(client), uri.getPath()); }
Example #24
Source File: TcpClientTransportTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@DisplayName("create throws NullPointerException with null client") @Test void createNullTcpClient() { assertThatNullPointerException() .isThrownBy(() -> TcpClientTransport.create((TcpClient) null)) .withMessage("client must not be null"); }
Example #25
Source File: BackendService.java From influx-proxy with Apache License 2.0 | 5 votes |
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 #26
Source File: ReactorNettyTcpClient.java From java-technology-stack with MIT License | 5 votes |
/** * Simple constructor with the host and port to use to connect to. * <p>This constructor manages the lifecycle of the {@link TcpClient} and * underlying resources such as {@link ConnectionProvider}, * {@link LoopResources}, and {@link ChannelGroup}. * <p>For full control over the initialization and lifecycle of the * TcpClient, use {@link #ReactorNettyTcpClient(TcpClient, ReactorNettyCodec)}. * @param host the host to connect to * @param port the port to connect to * @param codec for encoding and decoding the input/output byte streams * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec */ public ReactorNettyTcpClient(String host, int port, ReactorNettyCodec<P> codec) { Assert.notNull(host, "host is required"); Assert.notNull(codec, "ReactorNettyCodec is required"); this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); this.loopResources = LoopResources.create("tcp-client-loop"); this.poolResources = ConnectionProvider.elastic("tcp-client-pool"); this.codec = codec; this.tcpClient = TcpClient.create(this.poolResources) .host(host).port(port) .runOn(this.loopResources, false) .doOnConnected(conn -> this.channelGroup.add(conn.channel())); }
Example #27
Source File: HttpClientTcpConfig.java From reactor-netty with Apache License 2.0 | 4 votes |
@Override public TcpClient wiretap(String category, LogLevel level) { httpClient = httpClient.wiretap(category, level); return this; }
Example #28
Source File: DefaultPooledConnectionProviderTest.java From reactor-netty with Apache License 2.0 | 4 votes |
@Test public void testIssue673_TimeoutException() throws InterruptedException { DisposableServer server = TcpServer.create() .port(0) .handle((in, out) -> out.sendString(Mono.just("test") .delayElement(Duration.ofMillis(100)))) .wiretap(true) .bindNow(); DefaultPooledConnectionProvider provider = (DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue673_TimeoutException") .maxConnections(1) .pendingAcquireMaxCount(4) .pendingAcquireTimeout(Duration.ofMillis(10)) .build(); CountDownLatch latch = new CountDownLatch(2); try { AtomicReference<InstrumentedPool<PooledConnection>> pool = new AtomicReference<>(); List<? extends Signal<? extends Connection>> list = Flux.range(0, 5) .flatMapDelayError(i -> TcpClient.create(provider) .port(server.port()) .doOnConnected(conn -> { ConcurrentMap<PooledConnectionProvider.PoolKey, InstrumentedPool<PooledConnection>> pools = provider.channelPools; pool.set(pools.get(pools.keySet().toArray()[0])); }) .doOnDisconnected(conn -> latch.countDown()) .handle((in, out) -> in.receive().then()) .wiretap(true) .connect() .materialize(), 256, 32) .collectList() .doFinally(fin -> latch.countDown()) .block(Duration.ofSeconds(30)); assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch 30s").isTrue(); assertThat(list).isNotNull() .hasSize(5); int onNext = 0; int onError = 0; String msg = "Pool#acquire(Duration) has been pending for more than the configured timeout of 10ms"; for (int i = 0; i < 5; i++) { Signal<? extends Connection> signal = list.get(i); if (signal.isOnNext()) { onNext++; } else if (signal.getThrowable() instanceof TimeoutException && msg.equals(signal.getThrowable().getMessage())) { onError++; } } assertThat(onNext).isEqualTo(1); assertThat(onError).isEqualTo(4); assertThat(pool.get().metrics().acquiredSize()).as("currently acquired").isEqualTo(0); assertThat(pool.get().metrics().idleSize()).as("currently idle").isEqualTo(0); } finally { server.disposeNow(); provider.dispose(); } }
Example #29
Source File: ReactorNettyTcpClient.java From spring-analysis-note with MIT License | 4 votes |
/** * Constructor with an externally created {@link TcpClient} instance whose * lifecycle is expected to be managed externally. * @param tcpClient the TcpClient instance to use * @param codec for encoding and decoding the input/output byte streams * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec */ public ReactorNettyTcpClient(TcpClient tcpClient, ReactorNettyCodec<P> codec) { Assert.notNull(tcpClient, "TcpClient is required"); Assert.notNull(codec, "ReactorNettyCodec is required"); this.tcpClient = tcpClient; this.codec = codec; this.channelGroup = null; this.loopResources = null; this.poolResources = null; }
Example #30
Source File: ConnectionInfoTests.java From reactor-netty with Apache License 2.0 | 4 votes |
@Test public void proxyProtocolOn() throws InterruptedException { String remoteAddress = "202.112.144.236"; ArrayBlockingQueue<String> resultQueue = new ArrayBlockingQueue<>(1); Consumer<HttpServerRequest> requestConsumer = serverRequest -> { String remoteAddrFromRequest = serverRequest.remoteAddress().getHostString(); resultQueue.add(remoteAddrFromRequest); }; this.connection = HttpServer.create() .port(0) .proxyProtocol(ProxyProtocolSupportType.ON) .handle((req, res) -> { try { requestConsumer.accept(req); return res.status(200) .sendString(Mono.just("OK")); } catch (Throwable e) { return res.status(500) .sendString(Mono.just(e.getMessage())); } }) .wiretap(true) .bindNow(); Connection clientConn = TcpClient.create() .port(this.connection.port()) .connectNow(); ByteBuf proxyProtocolMsg = clientConn.channel() .alloc() .buffer(); proxyProtocolMsg.writeCharSequence("PROXY TCP4 " + remoteAddress + " 10.210.12.10 5678 80\r\n", Charset.defaultCharset()); proxyProtocolMsg.writeCharSequence("GET /test HTTP/1.1\r\nHost: a.example.com\r\n\r\n", Charset.defaultCharset()); clientConn.channel() .writeAndFlush(proxyProtocolMsg) .addListener(f -> { if (!f.isSuccess()) { fail("Writing proxyProtocolMsg was not successful"); } }); assertThat(resultQueue.poll(5, TimeUnit.SECONDS)).isEqualTo(remoteAddress); //send a http request again to confirm that removeAddress is not changed. ByteBuf httpMsg = clientConn.channel() .alloc() .buffer(); httpMsg.writeCharSequence("GET /test HTTP/1.1\r\nHost: a.example.com\r\n\r\n", Charset.defaultCharset()); clientConn.channel() .writeAndFlush(httpMsg) .addListener(f -> { if (!f.isSuccess()) { fail("Writing proxyProtocolMsg was not successful"); } }); assertThat(resultQueue.poll(5, TimeUnit.SECONDS)).isEqualTo(remoteAddress); }