Example usage for io.netty.channel.epoll EpollEventLoopGroup EpollEventLoopGroup

List of usage examples for io.netty.channel.epoll EpollEventLoopGroup EpollEventLoopGroup

Introduction

In this page you can find the example usage for io.netty.channel.epoll EpollEventLoopGroup EpollEventLoopGroup.

Prototype

public EpollEventLoopGroup(int nThreads, Executor executor) 

Source Link

Usage

From source file:alluxio.util.network.NettyUtils.java

License:Apache License

/**
 * Creates a Netty {@link EventLoopGroup} based on {@link ChannelType}.
 *
 * @param type Selector for which form of low-level IO we should use
 * @param numThreads target number of threads
 * @param threadPrefix name pattern for each thread. should contain '%d' to distinguish between
 *        threads./*from w  w w .  j  a  v a  2  s  .  c om*/
 * @param isDaemon if true, the {@link java.util.concurrent.ThreadFactory} will create daemon
 *        threads.
 * @return EventLoopGroup matching the ChannelType
 */
public static EventLoopGroup createEventLoop(ChannelType type, int numThreads, String threadPrefix,
        boolean isDaemon) {
    ThreadFactory threadFactory = ThreadFactoryUtils.build(threadPrefix, isDaemon);

    switch (type) {
    case NIO:
        return new NioEventLoopGroup(numThreads, threadFactory);
    case EPOLL:
        return new EpollEventLoopGroup(numThreads, threadFactory);
    default:
        throw new IllegalArgumentException("Unknown io type: " + type);
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingClient.java

License:Apache License

public NettyRemotingClient(final NettyClientConfig nettyClientConfig, //
        final ChannelEventListener channelEventListener) {
    super(nettyClientConfig.getClientOnewaySemaphoreValue(), nettyClientConfig.getClientAsyncSemaphoreValue());
    String name = SystemPropertyUtil.get("os.name").toLowerCase(Locale.UK).trim();
    isLinux = name.startsWith("linux");
    isLinux = false;//from w w  w  .  j a v  a 2s . c  o m
    this.nettyClientConfig = nettyClientConfig;
    this.channelEventListener = channelEventListener;

    int publicThreadNums = nettyClientConfig.getClientCallbackExecutorThreads();
    if (publicThreadNums <= 0) {
        publicThreadNums = 4;
    }

    this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyClientPublicExecutor_" + this.threadIndex.incrementAndGet());
        }
    });

    ThreadFactory workerThreadFactory = new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, String.format("NettyClientSelector_%d", this.threadIndex.incrementAndGet()));
        }
    };

    if (isLinux) {
        this.eventLoopGroupWorker = new EpollEventLoopGroup(1, workerThreadFactory);
    } else {
        this.eventLoopGroupWorker = new NioEventLoopGroup(1, workerThreadFactory);
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingServer.java

License:Apache License

public NettyRemotingServer(final NettyServerConfig nettyServerConfig,
        final ChannelEventListener channelEventListener) {
    super(nettyServerConfig.getServerOnewaySemaphoreValue(), nettyServerConfig.getServerAsyncSemaphoreValue());
    String name = SystemPropertyUtil.get("os.name").toLowerCase(Locale.UK).trim();
    isLinux = name.startsWith("linux");
    isLinux = false; //TODO: java.lang.UnsupportedOperationException: unsupported message type: OneMessageTransfer (expected: ByteBuf, DefaultFileRegion)
    this.serverBootstrap = new ServerBootstrap();
    this.nettyServerConfig = nettyServerConfig;
    this.channelEventListener = channelEventListener;

    int publicThreadNums = nettyServerConfig.getServerCallbackExecutorThreads();
    if (publicThreadNums <= 0) {
        publicThreadNums = 4;/*  w w w .  j  a va2 s  . c  o  m*/
    }

    this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyServerPublicExecutor_" + this.threadIndex.incrementAndGet());
        }
    });

    ThreadFactory bossThreadFactory = new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, String.format("NettyBossSelector_%d", this.threadIndex.incrementAndGet()));
        }
    };

    ThreadFactory workerThreadFactory = new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);
        private int threadTotal = nettyServerConfig.getServerSelectorThreads();

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, String.format("NettyServerSelector_%d_%d", threadTotal,
                    this.threadIndex.incrementAndGet()));
        }
    };

    if (isLinux) {
        this.eventLoopGroupBoss = new EpollEventLoopGroup(1, bossThreadFactory);
        this.eventLoopGroupWorker = new EpollEventLoopGroup(nettyServerConfig.getServerSelectorThreads(),
                workerThreadFactory);
    } else {
        this.eventLoopGroupBoss = new NioEventLoopGroup(1, bossThreadFactory);
        this.eventLoopGroupWorker = new NioEventLoopGroup(nettyServerConfig.getServerSelectorThreads(),
                workerThreadFactory);
    }
}

From source file:com.caricah.iotracah.server.netty.ServerImpl.java

License:Apache License

/**
 * The @link configure method is responsible for starting the implementation server processes.
 * The implementation should return once the server has started this allows
 * the launcher to maintain the life of the application.
 *
 * @throws UnRetriableException/*from  ww w.  jav a  2  s. c o m*/
 */
public void initiate() throws UnRetriableException {

    log.info(" configure : initiating the netty server.");

    try {

        int countOfAvailableProcessors = Runtime.getRuntime().availableProcessors() + 1;

        if (Epoll.isAvailable()) {
            bossEventLoopGroup = new EpollEventLoopGroup(2, getExecutorService());
            workerEventLoopGroup = new EpollEventLoopGroup(countOfAvailableProcessors, getExecutorService());

        } else {
            bossEventLoopGroup = new NioEventLoopGroup(2, getExecutorService());
            workerEventLoopGroup = new NioEventLoopGroup(countOfAvailableProcessors, getExecutorService());
        }

        //Initialize listener for TCP
        ServerBootstrap tcpBootstrap = new ServerBootstrap();
        tcpBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        tcpBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
        tcpBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

        tcpBootstrap = tcpBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

        if (Epoll.isAvailable()) {
            tcpBootstrap = tcpBootstrap.channel(EpollServerSocketChannel.class);
        } else {
            tcpBootstrap = tcpBootstrap.channel(NioServerSocketChannel.class);
        }

        tcpBootstrap = tcpBootstrap.handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(getServerInitializer(this, getConnectionTimeout()));

        ChannelFuture tcpChannelFuture = tcpBootstrap.bind(getTcpPort()).sync();
        tcpChannel = tcpChannelFuture.channel();

        if (isSslEnabled()) {
            //Initialize listener for SSL
            ServerBootstrap sslBootstrap = new ServerBootstrap();
            sslBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            sslBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
            sslBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

            sslBootstrap = sslBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

            if (Epoll.isAvailable()) {
                sslBootstrap = sslBootstrap.channel(EpollServerSocketChannel.class);
            } else {
                sslBootstrap = sslBootstrap.channel(NioServerSocketChannel.class);
            }

            sslBootstrap = sslBootstrap.handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(getServerInitializer(this, getConnectionTimeout(), getSslHandler()));

            ChannelFuture sslChannelFuture = sslBootstrap.bind(getSslPort()).sync();
            sslChannel = sslChannelFuture.channel();
        }

    } catch (InterruptedException e) {

        log.error(" configure : Initialization issues ", e);

        throw new UnRetriableException(e);

    }

}

From source file:com.github.sparkfy.network.util.NettyUtils.java

License:Apache License

/** Creates a Netty EventLoopGroup based on the IOMode. */
public static EventLoopGroup createEventLoop(IOMode mode, int numThreads, String threadPrefix) {
    ThreadFactory threadFactory = createThreadFactory(threadPrefix);

    switch (mode) {
    case NIO:/*w ww  .ja  va  2s  .  co m*/
        return new NioEventLoopGroup(numThreads, threadFactory);
    case EPOLL:
        return new EpollEventLoopGroup(numThreads, threadFactory);
    default:
        throw new IllegalArgumentException("Unknown io mode: " + mode);
    }
}

From source file:com.heliosapm.streams.onramp.OnRampBoot.java

License:Apache License

/**
 * Creates a new OnRampBoot/*from   w ww . j  av a 2 s .c  om*/
 * @param appConfig  The application configuration
 */
public OnRampBoot(final Properties appConfig) {
    final String jmxmpUri = ConfigurationHelper.getSystemThenEnvProperty("jmx.jmxmp.uri",
            "jmxmp://0.0.0.0:1893", appConfig);
    JMXHelper.fireUpJMXMPServer(jmxmpUri);
    MessageForwarder.initialize(appConfig);
    port = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.port", 8091, appConfig);
    bindInterface = ConfigurationHelper.getSystemThenEnvProperty("onramp.network.bind", "0.0.0.0", appConfig);
    bindSocket = new InetSocketAddress(bindInterface, port);
    workerThreads = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.worker_threads", CORES * 2,
            appConfig);
    connectTimeout = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sotimeout", 0, appConfig);
    backlog = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.backlog", 3072, appConfig);
    writeSpins = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.writespins", 16, appConfig);
    recvBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.recbuffer", 43690, appConfig);
    sendBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sendbuffer", 8192, appConfig);
    disableEpoll = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.epoll.disable", false,
            appConfig);
    async = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.async_io", true, appConfig);
    tcpNoDelay = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.tcp_no_delay", true,
            appConfig);
    keepAlive = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.keep_alive", true,
            appConfig);
    reuseAddress = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.reuse_address", true,
            appConfig);
    tcpPipelineFactory = new PipelineFactory(appConfig);
    udpPipelineFactory = new UDPPipelineFactory();
    tcpServerBootstrap.handler(new LoggingHandler(getClass(), LogLevel.INFO));
    tcpServerBootstrap.childHandler(tcpPipelineFactory);
    // Set the child options
    tcpServerBootstrap.childOption(ChannelOption.ALLOCATOR, BufferManager.getInstance().getAllocator());
    tcpServerBootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    tcpServerBootstrap.childOption(ChannelOption.SO_KEEPALIVE, keepAlive);
    tcpServerBootstrap.childOption(ChannelOption.SO_RCVBUF, recvBuffer);
    tcpServerBootstrap.childOption(ChannelOption.SO_SNDBUF, sendBuffer);
    tcpServerBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, writeSpins);
    // Set the server options
    tcpServerBootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    tcpServerBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    tcpServerBootstrap.option(ChannelOption.SO_RCVBUF, recvBuffer);
    tcpServerBootstrap.option(ChannelOption.SO_TIMEOUT, connectTimeout);

    final StringBuilder tcpUri = new StringBuilder("tcp");
    final StringBuilder udpUri = new StringBuilder("udp");
    if (IS_LINUX && !disableEpoll) {
        bossExecutorThreadFactory = new ExecutorThreadFactory("EpollServerBoss", true);
        bossGroup = new EpollEventLoopGroup(1, (ThreadFactory) bossExecutorThreadFactory);
        workerExecutorThreadFactory = new ExecutorThreadFactory("EpollServerWorker", true);
        workerGroup = new EpollEventLoopGroup(workerThreads, (ThreadFactory) workerExecutorThreadFactory);
        tcpChannelType = EpollServerSocketChannel.class;
        udpChannelType = EpollDatagramChannel.class;
        tcpUri.append("epoll");
        udpUri.append("epoll");
    } else {
        bossExecutorThreadFactory = new ExecutorThreadFactory("NioServerBoss", true);
        bossGroup = new NioEventLoopGroup(1, bossExecutorThreadFactory);
        workerExecutorThreadFactory = new ExecutorThreadFactory("NioServerWorker", true);
        workerGroup = new NioEventLoopGroup(workerThreads, workerExecutorThreadFactory);
        tcpChannelType = NioServerSocketChannel.class;
        udpChannelType = NioDatagramChannel.class;
        tcpUri.append("nio");
        udpUri.append("nio");
    }

    tcpUri.append("://").append(bindInterface).append(":").append(port);
    udpUri.append("://").append(bindInterface).append(":").append(port);
    URI u = null;
    try {
        u = new URI(tcpUri.toString());
    } catch (URISyntaxException e) {
        log.warn("Failed TCP server URI const: [{}]. Programmer Error", tcpUri, e);
    }
    tcpServerURI = u;
    try {
        u = new URI(udpUri.toString());
    } catch (URISyntaxException e) {
        log.warn("Failed UDP server URI const: [{}]. Programmer Error", udpUri, e);
    }
    udpServerURI = u;

    log.info(">>>>> Starting OnRamp TCP Listener on [{}]...", tcpServerURI);
    log.info(">>>>> Starting OnRamp UDP Listener on [{}]...", udpServerURI);
    final ChannelFuture cf = tcpServerBootstrap.channel(tcpChannelType).group(bossGroup, workerGroup)
            .bind(bindSocket).awaitUninterruptibly()
            .addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(final Future<? super Void> f) throws Exception {
                    log.info("<<<<< OnRamp TCP Listener on [{}] Started", tcpServerURI);
                };
            }).awaitUninterruptibly();
    final ChannelFuture ucf = udpBootstrap.channel(udpChannelType).group(workerGroup)
            .option(ChannelOption.SO_BROADCAST, true).handler(new UDPPipelineFactory()).bind(bindSocket)
            .awaitUninterruptibly().addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(final Future<? super Void> f) throws Exception {
                    log.info("<<<<< OnRamp UDP Listener on [{}] Started", udpServerURI);
                };
            }).awaitUninterruptibly();

    tcpServerChannel = cf.channel();
    udpServerChannel = ucf.channel();
    tcpCloseFuture = tcpServerChannel.closeFuture();
    udpCloseFuture = udpServerChannel.closeFuture();
    Runtime.getRuntime().addShutdownHook(shutdownHook);

}

From source file:com.linecorp.armeria.client.NonDecoratingClientFactory.java

License:Apache License

private static EventLoopGroup createGroup(Function<TransportType, ThreadFactory> threadFactoryFactory) {
    return NativeLibraries.isEpollAvailable()
            ? new EpollEventLoopGroup(0, threadFactoryFactory.apply(TransportType.EPOLL))
            : new NioEventLoopGroup(0, threadFactoryFactory.apply(TransportType.NIO));
}

From source file:com.linecorp.armeria.server.Server.java

License:Apache License

private void start(CompletableFuture<Void> future) {
    final State state = stateManager.state();
    switch (state.type) {
    case STOPPING:
        // A user called start() to restart the server, but the server is not stopped completely.
        // Try again after stopping.
        state.future.handle(voidFunction((ret, cause) -> start(future))).exceptionally(CompletionActions::log);
        return;/*from   ww w . j av a 2s.  c  o m*/
    }

    if (!stateManager.enterStarting(future, this::stop0)) {
        assert future.isCompletedExceptionally();
        return;
    }

    try {
        // Initialize the event loop groups.
        if (NativeLibraries.isEpollAvailable()) {
            final ThreadFactory bossThreadFactory = new DefaultThreadFactory("armeria-server-boss-epoll",
                    false);
            final ThreadFactory workerThreadFactory = new DefaultThreadFactory("armeria-server-epoll", false);
            bossGroup = new EpollEventLoopGroup(1, bossThreadFactory);
            workerGroup = new EpollEventLoopGroup(config.numWorkers(), workerThreadFactory);
        } else {
            final ThreadFactory bossThreadFactory = new DefaultThreadFactory("armeria-server-boss-nio", false);
            final ThreadFactory workerThreadFactory = new DefaultThreadFactory("armeria-server-nio", false);
            bossGroup = new NioEventLoopGroup(1, bossThreadFactory);
            workerGroup = new NioEventLoopGroup(config.numWorkers(), workerThreadFactory);
        }

        // Initialize the server sockets asynchronously.
        final List<ServerPort> ports = config().ports();
        final AtomicInteger remainingPorts = new AtomicInteger(ports.size());
        if (config().gracefulShutdownQuietPeriod().isZero()) {
            gracefulShutdownHandler = null;
        } else {
            gracefulShutdownHandler = GracefulShutdownHandler.create(config().gracefulShutdownQuietPeriod(),
                    config().blockingTaskExecutor());
        }

        for (ServerPort p : ports) {
            start(p).addListener(new ServerPortStartListener(remainingPorts, future, p));
        }
    } catch (Throwable t) {
        completeFutureExceptionally(future, t);
    }
}

From source file:com.mpush.netty.client.NettyTCPClient.java

License:Apache License

private void createEpollClient(Listener listener) {
    EpollEventLoopGroup workerGroup = new EpollEventLoopGroup(getWorkThreadNum(),
            new DefaultThreadFactory(ThreadNames.T_TCP_CLIENT));
    workerGroup.setIoRatio(getIoRate());
    createClient(listener, workerGroup, EpollSocketChannel::new);
}

From source file:com.mpush.netty.server.NettyServer.java

License:Apache License

@SuppressWarnings("unused")
private void createEpollServer(Listener listener) {
    EpollEventLoopGroup bossGroup = new EpollEventLoopGroup(1, getBossExecutor());
    EpollEventLoopGroup workerGroup = new EpollEventLoopGroup(0, getWorkExecutor());
    createServer(listener, bossGroup, workerGroup, EpollServerSocketChannel.class);
}