Search in sources :

Example 1 with EventLoop

use of io.netty.channel.EventLoop in project netty by netty.

the class UptimeClientHandler method channelUnregistered.

@Override
public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception {
    println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + 's');
    final EventLoop loop = ctx.channel().eventLoop();
    loop.schedule(new Runnable() {

        @Override
        public void run() {
            println("Reconnecting to: " + UptimeClient.HOST + ':' + UptimeClient.PORT);
            UptimeClient.connect(UptimeClient.configureBootstrap(new Bootstrap(), loop));
        }
    }, UptimeClient.RECONNECT_DELAY, TimeUnit.SECONDS);
}
Also used : EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 2 with EventLoop

use of io.netty.channel.EventLoop in project netty by netty.

the class NioSocketChannelTest method testChannelReRegisterRead.

private static void testChannelReRegisterRead(final boolean sameEventLoop) throws Exception {
    final EventLoopGroup group = new NioEventLoopGroup(2);
    final CountDownLatch latch = new CountDownLatch(1);
    // Just some random bytes
    byte[] bytes = new byte[1024];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);
    Channel sc = null;
    Channel cc = null;
    ServerBootstrap b = new ServerBootstrap();
    try {
        b.group(group).channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) {
                        // We was able to read something from the Channel after reregister.
                        latch.countDown();
                    }

                    @Override
                    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                        final EventLoop loop = group.next();
                        if (sameEventLoop) {
                            deregister(ctx, loop);
                        } else {
                            loop.execute(new Runnable() {

                                @Override
                                public void run() {
                                    deregister(ctx, loop);
                                }
                            });
                        }
                    }

                    private void deregister(ChannelHandlerContext ctx, final EventLoop loop) {
                        // As soon as the channel becomes active re-register it to another
                        // EventLoop. After this is done we should still receive the data that
                        // was written to the channel.
                        ctx.deregister().addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture cf) {
                                Channel channel = cf.channel();
                                assertNotSame(loop, channel.eventLoop());
                                group.next().register(channel);
                            }
                        });
                    }
                });
            }
        });
        sc = b.bind(0).syncUninterruptibly().channel();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInboundHandlerAdapter());
        cc = bootstrap.connect(sc.localAddress()).syncUninterruptibly().channel();
        cc.writeAndFlush(Unpooled.wrappedBuffer(bytes)).syncUninterruptibly();
        latch.await();
    } finally {
        if (cc != null) {
            cc.close();
        }
        if (sc != null) {
            sc.close();
        }
        group.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 3 with EventLoop

use of io.netty.channel.EventLoop in project grpc-java by grpc.

the class NettyHandlerTestBase method newMockContext.

protected final ChannelHandlerContext newMockContext() {
    ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    EventLoop eventLoop = Mockito.mock(EventLoop.class);
    when(ctx.executor()).thenReturn(eventLoop);
    return ctx;
}
Also used : EventLoop(io.netty.channel.EventLoop) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext)

Example 4 with EventLoop

use of io.netty.channel.EventLoop in project camel by apache.

the class ClientModeTCPNettyServerBootstrapFactory method scheduleReconnect.

private void scheduleReconnect(final ChannelFuture channelFuture) {
    final EventLoop loop = channelFuture.channel().eventLoop();
    loop.schedule(new Runnable() {

        @Override
        public void run() {
            try {
                LOG.trace("Re-connecting to {} if needed", configuration.getAddress());
                doReconnectIfNeeded();
            } catch (Exception e) {
                LOG.warn("Error during re-connect to " + configuration.getAddress() + ". Will attempt again in " + configuration.getReconnectInterval() + " millis. This exception is ignored.", e);
            }
        }
    }, configuration.getReconnectInterval(), TimeUnit.MILLISECONDS);
}
Also used : EventLoop(io.netty.channel.EventLoop) ConnectException(java.net.ConnectException)

Example 5 with EventLoop

use of io.netty.channel.EventLoop in project riposte by Nike-Inc.

the class AsyncHttpClientHelper method getCircuitBreaker.

protected Optional<CircuitBreaker<Response>> getCircuitBreaker(RequestBuilderWrapper requestBuilderWrapper) {
    if (requestBuilderWrapper.disableCircuitBreaker)
        return Optional.empty();
    // custom one is not specified.
    if (requestBuilderWrapper.customCircuitBreaker.isPresent())
        return requestBuilderWrapper.customCircuitBreaker;
    // No custom circuit breaker. Use the default for the given request's host.
    Uri uri = Uri.create(requestBuilderWrapper.url);
    String host = uri.getHost();
    EventLoop nettyEventLoop = requestBuilderWrapper.getCtx() == null ? null : requestBuilderWrapper.getCtx().channel().eventLoop();
    CircuitBreaker<Integer> defaultStatusCodeCircuitBreaker = getDefaultHttpStatusCodeCircuitBreakerForKey(host, Optional.ofNullable(nettyEventLoop), Optional.ofNullable(nettyEventLoop));
    return Optional.of(new CircuitBreakerDelegate<>(defaultStatusCodeCircuitBreaker, response -> (response == null ? null : response.getStatusCode())));
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Span(com.nike.wingtips.Span) CircuitBreakerDelegate(com.nike.fastbreak.CircuitBreakerDelegate) NameResolver(com.ning.http.client.NameResolver) ManualModeTask(com.nike.fastbreak.CircuitBreaker.ManualModeTask) LoggerFactory(org.slf4j.LoggerFactory) TraceHeaders(com.nike.wingtips.TraceHeaders) Tracer(com.nike.wingtips.Tracer) CompletableFuture(java.util.concurrent.CompletableFuture) Deque(java.util.Deque) CircuitBreakerOpenException(com.nike.fastbreak.exception.CircuitBreakerOpenException) ConcurrentMap(java.util.concurrent.ConcurrentMap) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) AsyncHttpClient(com.ning.http.client.AsyncHttpClient) AsyncHttpClientConfig(com.ning.http.client.AsyncHttpClientConfig) Response(com.ning.http.client.Response) Logger(org.slf4j.Logger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpMethod(io.netty.handler.codec.http.HttpMethod) CircuitBreakerForHttpStatusCode.getDefaultHttpStatusCodeCircuitBreakerForKey(com.nike.fastbreak.CircuitBreakerForHttpStatusCode.getDefaultHttpStatusCodeCircuitBreakerForKey) EventLoop(io.netty.channel.EventLoop) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) ChannelAttributes(com.nike.riposte.server.channelpipeline.ChannelAttributes) CircuitBreaker(com.nike.fastbreak.CircuitBreaker) MDC(org.slf4j.MDC) Optional(java.util.Optional) SignatureCalculator(com.ning.http.client.SignatureCalculator) Uri(com.ning.http.client.uri.Uri) EventLoop(io.netty.channel.EventLoop) Uri(com.ning.http.client.uri.Uri)

Aggregations

EventLoop (io.netty.channel.EventLoop)77 EventLoopGroup (io.netty.channel.EventLoopGroup)27 Test (org.junit.jupiter.api.Test)27 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)18 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)17 Channel (io.netty.channel.Channel)10 InetSocketAddress (java.net.InetSocketAddress)10 Bootstrap (io.netty.bootstrap.Bootstrap)9 InetAddress (java.net.InetAddress)9 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 ChannelFuture (io.netty.channel.ChannelFuture)6 ChannelPromise (io.netty.channel.ChannelPromise)6 LocalAddress (io.netty.channel.local.LocalAddress)5 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)4 ChannelPipeline (io.netty.channel.ChannelPipeline)4 ClosedChannelException (java.nio.channels.ClosedChannelException)4 SingleThreadEventLoop (io.netty.channel.SingleThreadEventLoop)3 IOException (java.io.IOException)3 UnknownHostException (java.net.UnknownHostException)3 Callable (java.util.concurrent.Callable)3