io.netty.handler.timeout.WriteTimeoutHandler Java Examples

The following examples show how to use io.netty.handler.timeout.WriteTimeoutHandler. 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: HandlerRemovingChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void removePerRequestHandlers(Channel channel) {
    channel.attr(IN_USE).set(false);

    // Only remove per request handler if the channel is registered
    // or open since DefaultChannelPipeline would remove handlers if
    // channel is closed and unregistered
    // See DefaultChannelPipeline.java#L1403
    if (channel.isOpen() || channel.isRegistered()) {
        removeIfExists(channel.pipeline(),
                       HttpStreamsClientHandler.class,
                       LastHttpContentHandler.class,
                       FlushOnReadHandler.class,
                       ResponseHandler.class,
                       ReadTimeoutHandler.class,
                       WriteTimeoutHandler.class);
    }
}
 
Example #2
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 #3
Source File: MonoSendManyTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testPromiseSendTimeout() {
	//use an extra handler
	EmbeddedChannel channel = new EmbeddedChannel(new WriteTimeoutHandler(1), new ChannelHandlerAdapter() {});

	Flux<String> flux = Flux.range(0, 257).map(count -> count + "");
	Mono<Void> m = MonoSendMany.objectSource(flux, channel, b -> false);

	StepVerifier.create(m)
	            .then(() -> {
	                channel.runPendingTasks(); //run flush
	                for (int i = 0; i < 257; i++) {
	                    assertThat(channel.<String>readOutbound()).isEqualTo(i + "");
	                }
	            })
	            .verifyComplete();
}
 
Example #4
Source File: HandlerRemovingChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    mockChannel = new MockChannel();
    pipeline = mockChannel.pipeline();
    pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
    nioEventLoopGroup = new NioEventLoopGroup();
    nioEventLoopGroup.register(mockChannel);
    RequestContext requestContext = new RequestContext(channelPool,
                                                       nioEventLoopGroup,
                                                       AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
                                                       null);

    mockChannel.attr(IN_USE).set(true);
    mockChannel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
    mockChannel.attr(RESPONSE_COMPLETE_KEY).set(true);

    pipeline.addLast(new HttpStreamsClientHandler());
    pipeline.addLast(ResponseHandler.getInstance());
    pipeline.addLast(new ReadTimeoutHandler(10));
    pipeline.addLast(new WriteTimeoutHandler(10));
    handlerRemovingChannelPool = new HandlerRemovingChannelPool(channelPool);
}
 
Example #5
Source File: NettyServer.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
@SneakyThrows
public void start(int port) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new WriteTimeoutHandler(30), new NettyServerHandler());
                    }
                });
        ChannelFuture future = bootstrap.bind().sync();
        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example #6
Source File: BaseNet.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Channel connect(ByteToMessageDecoder decoder) throws InterruptedException {
  NioEventLoopGroup group = new NioEventLoopGroup(1);
  Bootstrap b = new Bootstrap();
  b.group(group).channel(NioSocketChannel.class)
      .handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
          ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024));
          ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024);
          ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);
          ch.pipeline()
              .addLast("readTimeoutHandler", new ReadTimeoutHandler(600, TimeUnit.SECONDS))
              .addLast("writeTimeoutHandler", new WriteTimeoutHandler(600, TimeUnit.SECONDS));
          ch.pipeline().addLast("protoPender", new ProtobufVarint32LengthFieldPrepender());
          ch.pipeline().addLast("lengthDecode", new ProtobufVarint32FrameDecoder());
          ch.pipeline().addLast("handshakeHandler", decoder);
          ch.closeFuture();
        }
      }).option(ChannelOption.SO_KEEPALIVE, true)
      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000)
      .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
  return b.connect("127.0.0.1", port).sync().channel();
}
 
Example #7
Source File: OneNetChannelInitializer.java    From one-net with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline().addLast(new WriteTimeoutHandler(5))
            .addLast(new OneNetMsgEncoder())
            .addLast(new OneNetMsgDecoder())
            .addLast(new OneNetInboundHandler(serverSession));
}
 
Example #8
Source File: LocalChannelInitializer.java    From one-net with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();
    int bytesPreSecond = 0;
    if (clientSession != null) {
        bytesPreSecond = oneNetClientContext.getKBps() * OneNetCommonConstants.KByte;
    }
    p.addLast(new WriteTimeoutHandler(5))
            .addLast(CHANNEL_TRAFFIC_HANDLER, new ChannelTrafficShapingHandler(bytesPreSecond,
            bytesPreSecond))
            .addLast(LOCAL_RESPONSE_HANDLER, new LocalInboudHandler(oneNetClientContext, clientSession))
            .addLast(new ByteArrayEncoder());
}
 
Example #9
Source File: ReactorNettySenderTests.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void customReadTimeoutHonored(@WiremockResolver.Wiremock WireMockServer server) throws Throwable {
    this.httpSender = new ReactorNettySender(HttpClient.create()
            .tcpConfiguration(tcpClient -> tcpClient.doOnConnected(connection ->
                    connection.addHandlerLast(new ReadTimeoutHandler(1, TimeUnit.MILLISECONDS))
                            .addHandlerLast(new WriteTimeoutHandler(1, TimeUnit.MILLISECONDS)))));
    server.stubFor(any(urlEqualTo("/metrics")).willReturn(ok().withFixedDelay(5)));

    assertThatExceptionOfType(ReadTimeoutException.class)
            .isThrownBy(() -> httpSender.post(server.baseUrl() + "/metrics").send());
}
 
Example #10
Source File: NettyRequestExecutor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void writeRequest(HttpRequest request) {
    channel.pipeline().addFirst(new WriteTimeoutHandler(context.configuration().writeTimeoutMillis(),
                                                        TimeUnit.MILLISECONDS));
    StreamedRequest streamedRequest = new StreamedRequest(request,
                                                          context.executeRequest().requestContentPublisher());
    channel.writeAndFlush(streamedRequest)
           .addListener(wireCall -> {
               // Done writing so remove the idle write timeout handler
               ChannelUtils.removeIfExists(channel.pipeline(), WriteTimeoutHandler.class);
               if (wireCall.isSuccess()) {
                   if (context.executeRequest().fullDuplex()) {
                       return;
                   }

                   channel.pipeline().addFirst(new ReadTimeoutHandler(context.configuration().readTimeoutMillis(),
                                                                      TimeUnit.MILLISECONDS));
                   channel.read();

               } else {
                   // TODO: Are there cases where we can keep the channel open?
                   closeAndRelease(channel);
                   handleFailure(() -> "Failed to make request to " + endpoint(), wireCall.cause());
               }
           });

    if (shouldExplicitlyTriggerRead()) {

        // Should only add an one-time ReadTimeoutHandler to 100 Continue request.
        if (is100ContinueExpected()) {
            channel.pipeline().addFirst(new OneTimeReadTimeoutHandler(Duration.ofMillis(context.configuration()
                    .readTimeoutMillis())));
        } else {
            channel.pipeline().addFirst(new ReadTimeoutHandler(context.configuration().readTimeoutMillis(),
                                                               TimeUnit.MILLISECONDS));
        }

        channel.read();
    }
}
 
Example #11
Source File: NettyServer.java    From wind-im with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {
	// SSLEngine sslEngine =
	// NettySocketSslContext.getInstance().getServerContext().createSSLEngine();

	channel.pipeline().addLast(new MessageDecoder());
	channel.pipeline().addLast(new MessageEncoder());
	channel.pipeline().addLast("timeout", new IdleStateHandler(60 * 5, 60 * 5, 60 * 5, TimeUnit.SECONDS));

	// ch.pipeline().addLast(new SslHandler(sslEngine));

	channel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast("writeTimeoutHandler", new WriteTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast(new NettyServerHandler(executor));
}
 
Example #12
Source File: NettyServer.java    From openzaly with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {
	// SSLEngine sslEngine =
	// NettySocketSslContext.getInstance().getServerContext().createSSLEngine();

	channel.pipeline().addLast(new MessageDecoder());
	channel.pipeline().addLast(new MessageEncoder());
	channel.pipeline().addLast("timeout", new IdleStateHandler(60 * 5, 60 * 5, 60 * 5, TimeUnit.SECONDS));

	// ch.pipeline().addLast(new SslHandler(sslEngine));

	channel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast("writeTimeoutHandler", new WriteTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast(new NettyServerHandler(executor));
}
 
Example #13
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 #14
Source File: NettyServer.java    From openzaly with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {
	// SSLEngine sslEngine =
	// NettySocketSslContext.getInstance().getServerContext().createSSLEngine();

	channel.pipeline().addLast(new MessageDecoder());
	channel.pipeline().addLast(new MessageEncoder());
	channel.pipeline().addLast("timeout", new IdleStateHandler(60 * 5, 60 * 5, 60 * 5, TimeUnit.SECONDS));

	// ch.pipeline().addLast(new SslHandler(sslEngine));

	channel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast("writeTimeoutHandler", new WriteTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast(new NettyServerHandler(executor));
}
 
Example #15
Source File: BenchmarkHttpClient.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
  ChannelPipeline pipeline = ch.pipeline();

  if (sslContext != null) {
    pipeline.addLast("ssl", sslContext.newHandler(ch.alloc()));
  }

  pipeline.addLast(new ReadTimeoutHandler(60, TimeUnit.SECONDS))
    .addLast(new WriteTimeoutHandler(60, TimeUnit.SECONDS))
    .addLast(new HttpClientCodec())
    .addLast(new HttpObjectAggregator(65536))
    .addLast(new HttpClientHandler());
}
 
Example #16
Source File: TcpSession.java    From PacketLib with MIT License 5 votes vote down vote up
protected void refreshWriteTimeoutHandler(Channel channel) {
    if(channel != null) {
        if(this.writeTimeout <= 0) {
            if(channel.pipeline().get("writeTimeout") != null) {
                channel.pipeline().remove("writeTimeout");
            }
        } else {
            if(channel.pipeline().get("writeTimeout") == null) {
                channel.pipeline().addFirst("writeTimeout", new WriteTimeoutHandler(this.writeTimeout));
            } else {
                channel.pipeline().replace("writeTimeout", "writeTimeout", new WriteTimeoutHandler(this.writeTimeout));
            }
        }
    }
}
 
Example #17
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 #18
Source File: HandlerRemovingChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private void assertHandlersRemoved() {
    assertThat(pipeline.get(HttpStreamsClientHandler.class)).isNull();
    assertThat(pipeline.get(ResponseHandler.class)).isNull();
    assertThat(pipeline.get(ReadTimeoutHandler.class)).isNull();
    assertThat(pipeline.get(WriteTimeoutHandler.class)).isNull();
}
 
Example #19
Source File: HandlerRemovingChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private void assertHandlersNotRemoved() {
    assertThat(pipeline.get(HttpStreamsClientHandler.class)).isNotNull();
    assertThat(pipeline.get(ResponseHandler.class)).isNotNull();
    assertThat(pipeline.get(ReadTimeoutHandler.class)).isNotNull();
    assertThat(pipeline.get(WriteTimeoutHandler.class)).isNotNull();
}
 
Example #20
Source File: ChannelOperationsHandlerTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void publisherSenderOnCompleteFlushInProgress_3() {
	doTestPublisherSenderOnCompleteFlushInProgress(false, new WriteTimeoutHandler(1));
}
 
Example #21
Source File: ChannelOperationsHandlerTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void publisherSenderOnCompleteFlushInProgress_4() {
	doTestPublisherSenderOnCompleteFlushInProgress(true, new WriteTimeoutHandler(1));
}