Search in sources :

Example 81 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project jackrabbit-oak by apache.

the class ForwardHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    group = new NioEventLoopGroup(0, r -> {
        return new Thread(r, String.format("forward-handler-%d", threadNumber.getAndIncrement()));
    });
    Bootstrap b = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (flipPosition >= 0) {
                ch.pipeline().addLast(new FlipHandler(flipPosition));
            }
            if (skipBytes > 0) {
                ch.pipeline().addLast(new SkipHandler(skipPosition, skipBytes));
            }
            ch.pipeline().addLast(new BackwardHandler(ctx.channel()));
        }
    });
    remote = b.connect(targetHost, targetPort).sync().channel();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) LoggerFactory(org.slf4j.LoggerFactory) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) TimeUnit(java.util.concurrent.TimeUnit) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 82 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project jocean-http by isdom.

the class SignalTest method main.

/**
 * @param args
 * @throws Exception
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    final TestChannelPool pool = new TestChannelPool(1);
    final HttpClient httpClient = new DefaultHttpClient(new AbstractChannelCreator() {

        @Override
        protected void initializeBootstrap(final Bootstrap bootstrap) {
            bootstrap.group(new NioEventLoopGroup(1)).channel(NioSocketChannel.class);
        }
    }, pool, ENABLE_LOGGING, ENABLE_COMPRESSOR);
    final DefaultSignalClient client = new DefaultSignalClient(httpClient);
    client.registerRequestType(FetchPatientsRequest.class, FetchPatientsResponse.class, new URI("http://jumpbox.medtap.cn:8888"));
    client.registerRequestType(QueryMyPatientsForDoctorRequest.class, QueryMyPatientsForDoctorResponse.class, new URI("http://api.iplusmed.com"));
    client.registerRequestType(AddMultiMediasToJourneyRequest.class, AddMultiMediasToJourneyResponse.class, new URI("http://jumpbox.medtap.cn:8888"));
    {
        final QueryMyPatientsForDoctorRequest req = new QueryMyPatientsForDoctorRequest();
        req.setDoctorId("8510");
        ((SignalClient) client).interaction().request(req).<QueryMyPatientsForDoctorResponse>build().subscribe(new Subscriber<QueryMyPatientsForDoctorResponse>() {

            @Override
            public void onCompleted() {
                LOG.debug("FetchPatientsRequest: onCompleted.");
            }

            @Override
            public void onError(Throwable e) {
                LOG.debug("FetchPatientsRequest: onError: {}", ExceptionUtils.exception2detail(e));
            }

            @Override
            public void onNext(final QueryMyPatientsForDoctorResponse response) {
                LOG.debug("QueryMyPatientsForDoctorRequest: onNext: {}", response);
            }
        });
    }
    /*
        final CountDownLatch latch = new CountDownLatch(1);
        
        {
            final FetchPatientsRequest req = new FetchPatientsRequest();
            req.setAccountId("2");
            
            client.defineInteraction(req)
                .compose(RxNettys.<FetchPatientsResponse>filterProgress())
                .subscribe(new Subscriber<FetchPatientsResponse>() {
    
                @Override
                public void onCompleted() {
                    latch.countDown();
                    LOG.debug("FetchPatientsRequest: onCompleted.");
                }
    
                @Override
                public void onError(Throwable e) {
                    latch.countDown();
                    LOG.debug("FetchPatientsRequest: onError: {}", ExceptionUtils.exception2detail(e));
                }
    
                @Override
                public void onNext(final FetchPatientsResponse response) {
                    LOG.debug("FetchPatientsRequest: onNext: {}", response);
                }});
        }
        latch.await();
        pool.awaitRecycleChannels();
        */
    {
        final HttpUtil.TrafficCounterFeature trafficCounter = HttpUtil.buildTrafficCounterFeature();
        final HttpUtil.PayloadCounterFeature payloadCounter = HttpUtil.buildPayloadCounterFeature();
        final AddMultiMediasToJourneyRequest req = new AddMultiMediasToJourneyRequest();
        req.setCaseId("120");
        req.setJourneyId("1");
        final Subscription subscription = client.interaction().request(req).feature(// new Attachment("/Users/isdom/Desktop/997df3df73797e91dea4853c228fcbdee36ceb8a38cc8-1vxyhE_fw236.jpeg", "image/jpeg"))
        ENABLE_LOGGING, trafficCounter, payloadCounter, new Attachment("/Users/isdom/Pictures/IMG_3492.JPG", "image/jpeg")).<AddMultiMediasToJourneyResponse>build().subscribe(new Subscriber<AddMultiMediasToJourneyResponse>() {

            @Override
            public void onCompleted() {
                LOG.debug("AddMultiMediasToJourneyRequest: onCompleted.");
                LOG.debug("traffic: upload: {}/download: {}", trafficCounter.outboundBytes(), trafficCounter.inboundBytes());
                LOG.debug("payload: totalUpload: {}/totalDownload: {}", payloadCounter.totalUploadBytes(), payloadCounter.totalDownloadBytes());
            }

            @Override
            public void onError(Throwable e) {
                LOG.debug("AddMultiMediasToJourneyRequest: onError: {}", ExceptionUtils.exception2detail(e));
            }

            @Override
            public void onNext(final AddMultiMediasToJourneyResponse resp) {
                LOG.debug("AddMultiMediasToJourneyRequest: onNext: {}", resp);
            }
        });
        // subscription.unsubscribe();
        // TODO, why invoke onCompleted Event? not onError, check
        // TO BE CONTINUE, 2015-05-13
        LOG.debug("traffic: upload: {}/download: {}", trafficCounter.outboundBytes(), trafficCounter.inboundBytes());
        LOG.debug("payload: totalUpload: {}/totalDownload: {}", payloadCounter.totalUploadBytes(), payloadCounter.totalDownloadBytes());
    }
}
Also used : AbstractChannelCreator(org.jocean.http.client.impl.AbstractChannelCreator) Attachment(org.jocean.http.rosa.SignalClient.Attachment) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) Subscriber(rx.Subscriber) SignalClient(org.jocean.http.rosa.SignalClient) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) HttpClient(org.jocean.http.client.HttpClient) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) Bootstrap(io.netty.bootstrap.Bootstrap) Subscription(rx.Subscription) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 83 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project cdap by caskdata.

the class NettyRouterPipelineTest method testHttpPipelining.

@Test
public void testHttpPipelining() throws Exception {
    final BlockingQueue<HttpResponseStatus> responseStatuses = new LinkedBlockingQueue<>();
    EventLoopGroup eventGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventGroup).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
            pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof HttpResponse) {
                        responseStatuses.add(((HttpResponse) msg).status());
                    }
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    // Create a connection and make five consecutive HTTP call without waiting for the first to respond
    Channel channel = bootstrap.connect(HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME)).sync().channel();
    for (int i = 0; i < 5; i++) {
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v1/sleep?sleepMillis=3000");
        request.headers().set(HttpHeaderNames.HOST, HOSTNAME);
        channel.writeAndFlush(request);
    }
    // Should get the first response as normal one
    HttpResponseStatus status = responseStatuses.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpResponseStatus.OK, status);
    // The rest four should be failure responses
    for (int i = 0; i < 4; i++) {
        Assert.assertEquals(HttpResponseStatus.NOT_IMPLEMENTED, responseStatuses.poll(1, TimeUnit.SECONDS));
    }
    eventGroup.shutdownGracefully();
    channel.close();
    Assert.assertTrue(responseStatuses.isEmpty());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 84 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project alibaba-mom by younfor.

the class Broker method bind.

/**
 * 启动broker之前的netty服务器处理
 * @param port
 * @throws Exception
 */
public void bind(int port) throws Exception {
    // 启动消费进度定时任务
    // storeSubscribe(true, 5000);
    // scanSendInfotMap();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 3);
    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_BACKLOG, 1024 * 1024).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new RpcDecoder()).addLast(new RpcEncoder()).addLast(new SimpleChannelInboundHandler<Object>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object info) throws Exception {
                        if (InfoBodyConsumer.class.isInstance(info)) {
                            // 接受消费者订阅处理
                            processConsumer((InfoBodyConsumer) info, ctx);
                        } else if (ConsumeResult.class.isInstance(info)) {
                            // 收到消费者ConsumeResult
                            logger.debug(" 收到消费者ConsumeResult");
                            ConsumerGroup.confirmConsumer((ConsumeResult) info, ctx);
                        // confirmConsumer((ConsumeResult) info, ctx);
                        } else if (MessageSend.class.isInstance(info)) {
                            // System.out.println("收到消息");
                            MessageManager.recieveMsg((MessageSend) info, ctx);
                        // MessageManager.recieveMsg((LinkedBlockingQueue)info,ctx);
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        logger.error("broker 异常:");
                        // logger.error(cause.getMessage());
                        cause.printStackTrace();
                        ctx.close();
                    }
                });
            }
        });
        // 
        ChannelFuture future = serverBootstrap.bind(port).sync();
        logger.debug("mom服务启动成功...... 绑定端口" + port);
        // 等待服务端监听端口关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("smom服务抛出异常  " + e.getMessage());
    } finally {
        // 优雅退出 释放线程池资源
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        logger.debug("mom服务优雅的释放了线程资源...");
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) RpcEncoder(com.alibaba.middleware.race.mom.serializer.RpcEncoder) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RpcDecoder(com.alibaba.middleware.race.mom.serializer.RpcDecoder) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 85 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project ballerina by ballerina-lang.

the class DebugServer method startListening.

private void startListening() {
    int port = getDebugPort();
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new DebugServerInitializer(debugger));
        serverChannel = b.bind(port).sync().channel();
        PrintStream out = System.out;
        out.println(DebugConstants.DEBUG_MESSAGE + port);
        serverChannel.closeFuture().sync();
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    } catch (InterruptedException e) {
        // todo need to log the error.
        Thread.currentThread().interrupt();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : PrintStream(java.io.PrintStream) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Aggregations

NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)521 EventLoopGroup (io.netty.channel.EventLoopGroup)256 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)226 Bootstrap (io.netty.bootstrap.Bootstrap)184 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)178 SocketChannel (io.netty.channel.socket.SocketChannel)169 ChannelFuture (io.netty.channel.ChannelFuture)157 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)157 Channel (io.netty.channel.Channel)138 InetSocketAddress (java.net.InetSocketAddress)118 LoggingHandler (io.netty.handler.logging.LoggingHandler)87 ChannelPipeline (io.netty.channel.ChannelPipeline)84 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)73 SslContext (io.netty.handler.ssl.SslContext)64 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)49 IOException (java.io.IOException)49 EpollEventLoopGroup (io.netty.channel.epoll.EpollEventLoopGroup)47 ByteBuf (io.netty.buffer.ByteBuf)44 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)43 ChannelInitializer (io.netty.channel.ChannelInitializer)41