Search in sources :

Example 26 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project BRFS by zhangnianli.

the class AsyncTcpClientGroup method createClient.

@Override
public TcpClient<BaseMessage, BaseResponse> createClient(TcpClientConfig config, Executor executor) throws InterruptedException {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutMillis());
    if (executor == null) {
        executor = new Executor() {

            @Override
            public void execute(Runnable command) {
                command.run();
            }
        };
    }
    AsyncTcpClient client = new AsyncTcpClient(executor);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new IdleStateHandler(0, DEFAULT_WRITE_IDLE_TIMEOUT_SECONDS, 0)).addLast(new BaseMessageEncoder()).addLast(new BaseResponseDecoder()).addLast(new SimpleChannelInboundHandler<TokenMessage<BaseResponse>>() {

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, TokenMessage<BaseResponse> msg) throws Exception {
                    client.handle(msg.messageToken(), msg.message());
                }

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof IdleStateEvent) {
                        IdleStateEvent e = (IdleStateEvent) evt;
                        if (e.state() == IdleState.WRITER_IDLE) {
                            ctx.writeAndFlush(new BaseMessage(-1));
                        }
                    }
                }
            });
        }
    });
    ChannelFuture future = bootstrap.connect(config.remoteAddress()).sync();
    if (!future.isSuccess()) {
        return null;
    }
    Channel channel = future.channel();
    channelList.add(channel);
    channel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            channelList.remove(channel);
        }
    });
    LOG.info("create tcp client for {}", config.remoteAddress());
    client.attach(channel);
    return client;
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) TokenMessage(com.bonree.brfs.common.net.tcp.TokenMessage) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFutureListener(io.netty.channel.ChannelFutureListener) IOException(java.io.IOException) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) BaseResponse(com.bonree.brfs.common.net.tcp.BaseResponse) Executor(java.util.concurrent.Executor) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) BaseMessage(com.bonree.brfs.common.net.tcp.BaseMessage) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 27 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project BRFS by zhangnianli.

the class MessageChannelInitializer method initChannel.

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(DEFAULT_READ_IDLE_TIMEOUT_SECONDS, 0, 0));
    pipeline.addLast(new MessageResponseEncoder());
    pipeline.addLast(new MessageProtocolDecoder());
    pipeline.addLast(messageDispatcher);
}
Also used : IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 28 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project ambry by linkedin.

the class FrontendNettyChannelInitializer method initChannel.

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // If channel handler implementations are not annotated with @Sharable, Netty creates a new instance of every class
    // in the pipeline for every connection.
    // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances.
    ChannelPipeline pipeline = ch.pipeline();
    // connection stats handler to track connection related metrics
    pipeline.addLast("connectionStatsHandler", connectionStatsHandler);
    // if SSL is enabled, add an SslHandler before the HTTP codec
    if (sslFactory != null) {
        InetSocketAddress peerAddress = ch.remoteAddress();
        String peerHost = peerAddress.getHostName();
        int peerPort = peerAddress.getPort();
        SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER));
        pipeline.addLast("sslHandler", sslHandler);
    }
    pipeline.addLast("codec", new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength, nettyConfig.nettyServerMaxHeaderSize, nettyConfig.nettyServerMaxChunkSize)).addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics)).addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics)).addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds)).addLast("chunker", new ChunkedWriteHandler());
    if (addedChannelHandlers != null) {
        pipeline.addLast(addedChannelHandlers.toArray(new ChannelHandler[0]));
    }
    // custom processing class that interfaces with a RestRequestService.
    pipeline.addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, performanceConfig, requestHandler));
}
Also used : ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) InetSocketAddress(java.net.InetSocketAddress) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Example 29 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project java by wavefrontHQ.

the class ProxyUtil method createInitializer.

/**
 * Create a {@link ChannelInitializer} with multiple dynamically created
 * {@link ChannelHandler} objects.
 *
 * @param channelHandlerSuppliers Suppliers of ChannelHandlers.
 * @param port                    port number.
 * @param idleTimeout             idle timeout in seconds.
 * @param sslContext              SSL context.
 * @return channel initializer
 */
static ChannelInitializer<SocketChannel> createInitializer(Iterable<Supplier<ChannelHandler>> channelHandlerSuppliers, int port, int idleTimeout, @Nullable SslContext sslContext) {
    String strPort = String.valueOf(port);
    ChannelHandler idleStateEventHandler = new IdleStateEventHandler(Metrics.newCounter(new TaggedMetricName("listeners", "connections.idle.closed", "port", strPort)));
    ChannelHandler connectionTracker = new ConnectionTrackingHandler(Metrics.newCounter(new TaggedMetricName("listeners", "connections.accepted", "port", strPort)), Metrics.newCounter(new TaggedMetricName("listeners", "connections.active", "port", strPort)));
    if (sslContext != null) {
        logger.info("TLS enabled on port: " + port);
    }
    return new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(ch.alloc()));
            }
            pipeline.addFirst("idlehandler", new IdleStateHandler(idleTimeout, 0, 0));
            pipeline.addLast("idlestateeventhandler", idleStateEventHandler);
            pipeline.addLast("connectiontracker", connectionTracker);
            channelHandlerSuppliers.forEach(x -> pipeline.addLast(x.get()));
        }
    };
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) IdleStateEventHandler(com.wavefront.agent.channel.IdleStateEventHandler) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ChannelHandler(io.netty.channel.ChannelHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) TaggedMetricName(com.wavefront.common.TaggedMetricName) ChannelPipeline(io.netty.channel.ChannelPipeline) ConnectionTrackingHandler(com.wavefront.agent.channel.ConnectionTrackingHandler)

Example 30 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project apollo by apollo-rsps.

the class ServiceChannelInitializer method initChannel.

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("handshakeDecoder", new HandshakeDecoder());
    pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0));
    pipeline.addLast("handler", handler);
}
Also used : IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HandshakeDecoder(org.apollo.net.codec.handshake.HandshakeDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Aggregations

IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)70 ChannelPipeline (io.netty.channel.ChannelPipeline)35 SocketChannel (io.netty.channel.socket.SocketChannel)18 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)14 LoggingHandler (io.netty.handler.logging.LoggingHandler)14 SslHandler (io.netty.handler.ssl.SslHandler)14 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)12 ChannelFuture (io.netty.channel.ChannelFuture)10 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)10 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 EventLoopGroup (io.netty.channel.EventLoopGroup)8 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)7 HttpServerCodec (io.netty.handler.codec.http.HttpServerCodec)7 IdleStateEvent (io.netty.handler.timeout.IdleStateEvent)7 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)6 Channel (io.netty.channel.Channel)6 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 SslContext (io.netty.handler.ssl.SslContext)6 InetSocketAddress (java.net.InetSocketAddress)6