Example usage for io.netty.util.concurrent GlobalEventExecutor INSTANCE

List of usage examples for io.netty.util.concurrent GlobalEventExecutor INSTANCE

Introduction

In this page you can find the example usage for io.netty.util.concurrent GlobalEventExecutor INSTANCE.

Prototype

GlobalEventExecutor INSTANCE

To view the source code for io.netty.util.concurrent GlobalEventExecutor INSTANCE.

Click Source Link

Usage

From source file:channel.group.ClientHandler.java

public static void createGroup(String groupID) {
    ClientChannelGroup ccg = new ClientChannelGroup(groupID, GlobalEventExecutor.INSTANCE);
    serverGroup.put(groupID, ccg);// w w  w  .  j  a  v a  2 s. c  om
}

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group)
        throws IOException {
    super();//from  w w w.j  ava  2 s .  c  om
    this.group = group;
    this.rootDir = rootDir;
    this.filesystems = loadFileSystems(rootDir);
    this.serverPeers = new AtomicInteger(0);
    bossGroup = new NioEventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap()
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK)
            .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch));
                }
            });
    /* bind to one or more interfaces, if supplied, otherwise all */
    if ((netif == null) || (netif.length == 0)) {
        ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port))
                .syncUninterruptibly().channel();
        serverLocal = serverChannel.localAddress();
    } else {
        InetSocketAddress primaryServerLocal = null;
        for (String net : netif) {
            NetworkInterface nicif = NetworkInterface.getByName(net);
            if (nicif == null) {
                log.warn("missing speficied NIC: {}", net);
                continue;
            }
            for (InterfaceAddress addr : nicif.getInterfaceAddresses()) {
                InetAddress inAddr = addr.getAddress();
                if (inAddr.getAddress().length != 4) {
                    log.trace("skip non-ipV4 address: {}", inAddr);
                    continue;
                }
                ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap
                        .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel();
                if (primaryServerLocal != null) {
                    log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal);
                }
                primaryServerLocal = serverChannel.localAddress();
            }
        }
        if (primaryServerLocal == null) {
            throw new IllegalArgumentException("no valid interface / port specified");
        }
        serverLocal = primaryServerLocal;
    }
    this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress());
    this.serverPort = serverLocal.getPort();
    if (serverNetIf != null) {
        serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName();
    } else {
        serverUuid = super.getUUID() + "-" + serverPort;
    }
    log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir);
    closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
    workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> {
        bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> {
            if (!workerFuture.isSuccess()) {
                closeFuture.tryFailure(workerFuture.cause());
            } else if (!bossFuture.isSuccess()) {
                closeFuture.tryFailure(bossFuture.cause());
            } else {
                closeFuture.trySuccess(null);
            }
        });
    });
    addMessageFileSystemPaths();
    group.join(this);
    if (autoMesh) {
        startAutoMesh(serverPort, autoMeshTimeout);
    }
}

From source file:com.barchart.netty.server.base.AbstractServer.java

License:BSD License

@Override
public ChannelFuture listen(final SocketAddress address) {

    shutdownFuture = new DefaultPromise<T>(GlobalEventExecutor.INSTANCE);

    final ChannelFuture future = bootstrap().bind(address);

    serverChannels.add(future.channel());

    return future;

}

From source file:com.barchart.netty.server.base.AbstractStatefulServer.java

License:BSD License

@Override
protected Future<?> shutdownEventLoop() {

    if (childGroup != defaultGroup)
        return new TimeoutPromiseGroup(GlobalEventExecutor.INSTANCE,
                childGroup.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS), super.shutdownEventLoop());

    return super.shutdownEventLoop();

}

From source file:com.cloudhopper.smpp.impl.DefaultSmppClient.java

License:Apache License

/**
 * Creates a new default SmppClient./*from  w  ww .  j  a v  a2s.  co m*/
 * @param workerGroup The max number of concurrent sessions expected
 *      to be active at any time.  This number controls the max number of worker
 *      threads that the underlying Netty library will use.  If processing
 *      occurs in a sessionHandler (a blocking op), be <b>VERY</b> careful
 *      setting this to the correct number of concurrent sessions you expect.
 * @param monitorExecutor The scheduled executor that all sessions will share
 *      to monitor themselves and expire requests.  If null monitoring will
 *      be disabled.
 */
public DefaultSmppClient(NioEventLoopGroup workerGroup, ScheduledExecutorService monitorExecutor) {
    this.channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    this.workerGroup = workerGroup;
    this.clientBootstrap = new Bootstrap();
    this.clientBootstrap.group(this.workerGroup);
    this.clientBootstrap.channel(NioSocketChannel.class);
    // we use the same default pipeline for all new channels - no need for a factory
    this.clientConnector = new SmppClientConnector(this.channels);

    this.clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(SmppChannelConstants.PIPELINE_CLIENT_CONNECTOR_NAME, clientConnector);
        }
    });

    this.monitorExecutor = monitorExecutor;
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppServer.java

License:Apache License

/**
 * Creates a new default SmppServer.// w w  w.j  a  v a 2s .  c  om
 * @param configuration The server configuration to create this server with
 * @param serverHandler The handler implementation for handling bind requests
 *      and creating/destroying sessions.
 * @param monitorExecutor The scheduled executor that all sessions will share
 *      to monitor themselves and expire requests. If null monitoring will
 *      be disabled.
 * @param bossGroup Specify the EventLoopGroup to accept new connections and
 *      handle accepted connections. The {@link EventLoopGroup} is used to handle
 *      all the events and IO for {@link SocketChannel}.
 * @param workerGroup The {@link EventLoopGroup} is used to handle all the events
 *      and IO for {@link Channel}.
 */
public DefaultSmppServer(final SmppServerConfiguration configuration, SmppServerHandler serverHandler,
        ScheduledExecutorService monitorExecutor, EventLoopGroup bossGroup, EventLoopGroup workerGroup) {
    this.configuration = configuration;
    // the same group we'll put every server channel
    this.channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    this.serverHandler = serverHandler;

    // tie the server bootstrap to this server socket channel factory
    this.serverBootstrap = new ServerBootstrap();

    // a factory for creating channels (connections)
    if (configuration.isNonBlockingSocketsEnabled()) {
        this.serverBootstrap.channel(NioServerSocketChannel.class);
    } else {
        this.serverBootstrap.channel(OioServerSocketChannel.class);
    }

    this.bossGroup = bossGroup;
    this.workerGroup = workerGroup;
    this.serverBootstrap.group(this.bossGroup, this.workerGroup);

    // set options for the server socket that are useful
    this.serverBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());

    // we use the same default pipeline for all new channels - no need for a factory
    this.serverConnector = new SmppServerConnector(channels, this);

    this.serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(SmppChannelConstants.PIPELINE_SERVER_CONNECTOR_NAME, serverConnector);
        }
    });

    // a shared timer used to make sure new channels are bound within X milliseconds
    this.bindTimer = new Timer(configuration.getName() + "-BindTimer0", true);
    // NOTE: this would permit us to customize the "transcoding" context for a server if needed
    this.transcoder = new DefaultPduTranscoder(new DefaultPduTranscoderContext());
    this.sessionIdSequence = new AtomicLong(0);
    this.monitorExecutor = monitorExecutor;
    this.counters = new DefaultSmppServerCounters();
    if (configuration.isJmxEnabled()) {
        registerMBean();
    }
}

From source file:com.cloudhopper.smpp.simulator.SmppSimulatorServer.java

License:Apache License

public SmppSimulatorServer() {
    // used for tracking any child channels (sessions)
    this.sessionChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    // we'll put the "boss" worker for a server in its own pool
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    // tie the server bootstrap to this server socket channel factory
    this.serverBootstrap = new ServerBootstrap();
    this.serverBootstrap.channel(NioServerSocketChannel.class);
    this.serverBootstrap.group(bossGroup, workerGroup);

    // the handler to use when new child connections are accepted
    this.serverHandler = new SmppSimulatorServerHandler(this.sessionChannels);
    // set up the event pipeline factory for new connections
    this.serverBootstrap.childHandler(serverHandler);
}

From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.InboundWebSocketConnection.java

License:Apache License

/**
 * {@inheritDoc}//from ww w  .  j  a v a  2  s.c o m
 */
@Override
public void start(final ConnectionConfig config) {
    URI endpoint = URI.create(config.getEndpoint());

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    connectedChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(
            new WebSocketServerInitializer(endpoint, connectionMonitor, config, connectedChannels));

    try {
        serverBootstrap.bind(endpoint.getPort()).sync().channel();
        LOG.info("Web socket server started at port {}.", endpoint.getPort());
    } catch (InterruptedException e) {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

        throw new IllegalStateException("Error starting web socket endpoint.", e);
    }
}

From source file:com.eluup.flume.sink.elasticsearch.client.PreBuiltTransportClient.java

License:Apache License

@Override
public void close() {
    super.close();
    if (NetworkModule.TRANSPORT_TYPE_SETTING.exists(settings) == false
            || NetworkModule.TRANSPORT_TYPE_SETTING.get(settings).equals(Netty4Plugin.NETTY_TRANSPORT_NAME)) {
        try {//  w  ww. ja  v  a 2  s .co m
            GlobalEventExecutor.INSTANCE.awaitInactivity(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        try {
            ThreadDeathWatcher.awaitInactivity(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.github.milenkovicm.kafka.KafkaProducer.java

License:Apache License

public KafkaProducer(String hostname, int port, String topicName, ProducerProperties properties,
        EventLoopGroup workerGroup) {/* w w w.  java 2s.  c  o m*/
    this.properties = properties;
    this.hostname = hostname;
    this.port = port;
    this.topicName = topicName;
    this.workerGroup = workerGroup;

    this.kafkaTopic = new KafkaTopic(properties.get(ProducerProperties.PARTITIONER), properties, topicName);

    this.eventExecutor = GlobalEventExecutor.INSTANCE;
    this.connectPromise = new DefaultPromise<>(eventExecutor);
    this.disconnectPromise = new DefaultPromise<>(eventExecutor);

}