Example usage for io.netty.channel.nio NioEventLoopGroup next

List of usage examples for io.netty.channel.nio NioEventLoopGroup next

Introduction

In this page you can find the example usage for io.netty.channel.nio NioEventLoopGroup next.

Prototype

@Override
    public EventLoop next() 

Source Link

Usage

From source file:chat.viska.xmpp.Connection.java

License:Apache License

private static Single<List<DnsRecord>> lookupDnsUsingNetty(final String query, final DnsRecordType type,
        @Nullable final Iterable<String> dns) {
    final NioEventLoopGroup threadPool = new NioEventLoopGroup();
    final DnsNameResolverBuilder builder = new DnsNameResolverBuilder(threadPool.next());
    builder.channelFactory(new ReflectiveChannelFactory<>(NioDatagramChannel.class));
    builder.decodeIdn(true);//  ww w. j  a v a  2  s  .  com
    if (dns != null) {
        builder.searchDomains(dns);
    }
    return Single.fromFuture(builder.build().query(new DefaultDnsQuestion(query, type)))
            .map(AddressedEnvelope::content).map(message -> {
                final int recordsSize = message.count(DnsSection.ANSWER);
                final List<DnsRecord> records = new ArrayList<>(recordsSize);
                for (int it = 0; it < recordsSize; ++it) {
                    records.add(message.recordAt(DnsSection.ANSWER, it));
                }
                return records;
            }).doFinally(threadPool::shutdownGracefully);
}

From source file:com.lambdaworks.redis.resource.DefaultClientResourcesTest.java

License:Apache License

@Test
public void testDefaults() throws Exception {

    DefaultClientResources sut = DefaultClientResources.create();

    assertThat(sut.commandLatencyCollector()).isNotNull();
    assertThat(sut.commandLatencyCollector().isEnabled()).isTrue();

    EventExecutorGroup eventExecutors = sut.eventExecutorGroup();
    NioEventLoopGroup eventLoopGroup = sut.eventLoopGroupProvider().allocate(NioEventLoopGroup.class);

    eventExecutors.next().submit(mock(Runnable.class));
    eventLoopGroup.next().submit(mock(Runnable.class));

    assertThat(sut.shutdown(0, 0, TimeUnit.SECONDS).get()).isTrue();

    assertThat(eventExecutors.isTerminated()).isTrue();
    assertThat(eventLoopGroup.isTerminated()).isTrue();

    Future<Boolean> shutdown = sut.eventLoopGroupProvider().shutdown(0, 0, TimeUnit.SECONDS);
    assertThat(shutdown.get()).isTrue();

    assertThat(sut.commandLatencyCollector().isEnabled()).isFalse();
}

From source file:com.linkedin.r2.transport.http.client.AbstractNettyStreamClient.java

License:Apache License

/**
 * Creates a new HttpNettyClient/*  w  w w  .  jav  a 2s.  c om*/
 *
 * @param eventLoopGroup            The NioEventLoopGroup; it is the caller's responsibility to
 *                                  shut it down
 * @param executor                  An executor; it is the caller's responsibility to shut it down
 * @param requestTimeout            Timeout, in ms, to get a connection from the pool or create one
 * @param shutdownTimeout           Timeout, in ms, the client should wait after shutdown is
 *                                  initiated before terminating outstanding requests
 * @param maxResponseSize           Maximum size of a HTTP response
 * @param callbackExecutors         An optional EventExecutorGroup to invoke user callback
 * @param jmxManager                A management class that is aware of the creation/shutdown event
 *                                  of the underlying {@link ChannelPoolManager}
 * @param maxConcurrentConnections  Maximum number of concurrent connection attempts the HTTP
 *                                  connection pool can make.
 */
public AbstractNettyStreamClient(NioEventLoopGroup eventLoopGroup, ScheduledExecutorService executor,
        long requestTimeout, long shutdownTimeout, long maxResponseSize, ExecutorService callbackExecutors,
        AbstractJmxManager jmxManager, int maxConcurrentConnections) {
    _maxResponseSize = maxResponseSize;
    _maxConcurrentConnections = maxConcurrentConnections;
    _scheduler = executor;
    _callbackExecutors = callbackExecutors == null ? eventLoopGroup : callbackExecutors;
    _requestTimeout = requestTimeout;
    _shutdownTimeout = shutdownTimeout;
    _requestTimeoutMessage = "Exceeded request timeout of " + _requestTimeout + "ms";
    _jmxManager = jmxManager;
    _allChannels = new DefaultChannelGroup("R2 client channels", eventLoopGroup.next());
}

From source file:com.linkedin.r2.transport.http.client.HttpNettyClient.java

License:Apache License

/**
 * Creates a new HttpNettyClient//ww w  .j  a va 2s  .  c om
 *
 * @param eventLoopGroup            The NioEventLoopGroup; it is the caller's responsibility to
 *                                  shut it down
 * @param executor                  An executor; it is the caller's responsibility to shut it down
 * @param poolSize                  Maximum size of the underlying HTTP connection pool
 * @param requestTimeout            Timeout, in ms, to get a connection from the pool or create one
 * @param idleTimeout               Interval after which idle connections will be automatically closed
 * @param shutdownTimeout           Timeout, in ms, the client should wait after shutdown is
 *                                  initiated before terminating outstanding requests
 * @param maxResponseSize           Maximum size of a HTTP response
 * @param sslContext                {@link SSLContext}
 * @param sslParameters             {@link SSLParameters}with overloaded construct
 * @param callbackExecutors         An optional EventExecutorGroup to invoke user callback
 * @param poolWaiterSize            Maximum waiters waiting on the HTTP connection pool
 * @param name                      Name of the {@link HttpNettyClient}
 * @param jmxManager                A management class that is aware of the creation/shutdown event
 *                                  of the underlying {@link ChannelPoolManager}
 * @param strategy                  The strategy used to return pool objects.
 * @param minPoolSize               Minimum number of objects in the pool. Set to zero for no minimum.
 * @param maxHeaderSize             Maximum size of all HTTP headers
 * @param maxChunkSize              Maximum size of a HTTP chunk
 * @param maxConcurrentConnections  Maximum number of concurrent connection attempts the HTTP
 *                                  connection pool can make.
 */
public HttpNettyClient(NioEventLoopGroup eventLoopGroup, ScheduledExecutorService executor, int poolSize,
        long requestTimeout, long idleTimeout, long shutdownTimeout, int maxResponseSize, SSLContext sslContext,
        SSLParameters sslParameters, ExecutorService callbackExecutors, int poolWaiterSize, String name,
        AbstractJmxManager jmxManager, AsyncPoolImpl.Strategy strategy, int minPoolSize, int maxHeaderSize,
        int maxChunkSize, int maxConcurrentConnections) {
    Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
            .handler(new HttpClientPipelineInitializer(sslContext, sslParameters));

    _channelPoolManager = new ChannelPoolManager(
            new ChannelPoolFactoryImpl(bootstrap, poolSize, idleTimeout, poolWaiterSize, strategy, minPoolSize),
            name + ChannelPoolManager.BASE_NAME);

    _maxResponseSize = maxResponseSize;
    _maxHeaderSize = maxHeaderSize;
    _maxChunkSize = maxChunkSize;
    _maxConcurrentConnections = maxConcurrentConnections;
    _scheduler = executor;
    _callbackExecutors = callbackExecutors == null ? eventLoopGroup : callbackExecutors;
    _requestTimeout = requestTimeout;
    _shutdownTimeout = shutdownTimeout;
    _requestTimeoutMessage = "Exceeded request timeout of " + _requestTimeout + "ms";
    _jmxManager = jmxManager;
    _allChannels = new DefaultChannelGroup("R2 client channels", eventLoopGroup.next());
    _jmxManager.onProviderCreate(_channelPoolManager);
}

From source file:org.apache.hive.spark.client.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *///from  w  w w .  j  a  v a  2s.  c o  m
public static Promise<Rpc> createClient(Map<String, String> config, final NioEventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    final RpcConfiguration rpcConf = new RpcConfiguration(config);
    int connectTimeoutMs = (int) rpcConf.getConnectTimeoutMs();

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask, rpcConf.getServerConnectTimeoutMs(),
            TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(rpcConf, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(rpcConf, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}