Java Code Examples for org.jboss.netty.bootstrap.ServerBootstrap#setPipelineFactory()

The following examples show how to use org.jboss.netty.bootstrap.ServerBootstrap#setPipelineFactory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ShuffleHandler.java    From tez with Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {
  ServerBootstrap bootstrap = new ServerBootstrap(selector);
  try {
    pipelineFact = new HttpPipelineFactory(conf);
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
  bootstrap.setPipelineFactory(pipelineFact);
  port = conf.getInt(SHUFFLE_PORT_CONFIG_KEY, DEFAULT_SHUFFLE_PORT);
  Channel ch = bootstrap.bind(new InetSocketAddress(port));
  accepted.add(ch);
  port = ((InetSocketAddress)ch.getLocalAddress()).getPort();
  conf.set(SHUFFLE_PORT_CONFIG_KEY, Integer.toString(port));
  pipelineFact.SHUFFLE.setPort(port);
  LOG.info("TezShuffleHandler" + " listening on port " + port);
}
 
Example 2
Source File: TestDelegationTokenRemoteFetcher.java    From big-c with Apache License 2.0 6 votes vote down vote up
private ServerBootstrap startHttpServer(int port,
    final Token<DelegationTokenIdentifier> token, final URI url) {
  ServerBootstrap bootstrap = new ServerBootstrap(
      new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new HttpRequestDecoder(),
          new HttpChunkAggregator(65536), new HttpResponseEncoder(),
          new CredentialsLogicHandler(token, url.toString()));
    }
  });
  bootstrap.bind(new InetSocketAddress("localhost", port));
  return bootstrap;
}
 
Example 3
Source File: NettyConnector.java    From netty-servlet with Apache License 2.0 6 votes vote down vote up
@Override
public NettyConnector start() throws Exception {
    bootstrap = new ServerBootstrap(
            new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new HttpServerPipelineFactory(getDispatcher()));

    bootstrap.setOption("child.tcpNoDelay", true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(new InetSocketAddress(getPort()));
    return this;
}
 
Example 4
Source File: TestDelegationTokenRemoteFetcher.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private ServerBootstrap startHttpServer(int port,
    final Token<DelegationTokenIdentifier> token, final URI url) {
  ServerBootstrap bootstrap = new ServerBootstrap(
      new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new HttpRequestDecoder(),
          new HttpChunkAggregator(65536), new HttpResponseEncoder(),
          new CredentialsLogicHandler(token, url.toString()));
    }
  });
  bootstrap.bind(new InetSocketAddress("localhost", port));
  return bootstrap;
}
 
Example 5
Source File: ShuffleHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
protected void serviceStart() throws Exception {
  Configuration conf = getConfig();
  userRsrc = new ConcurrentHashMap<String,String>();
  secretManager = new JobTokenSecretManager();
  recoverState(conf);
  ServerBootstrap bootstrap = new ServerBootstrap(selector);
  try {
    pipelineFact = new HttpPipelineFactory(conf);
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
  bootstrap.setPipelineFactory(pipelineFact);
  port = conf.getInt(SHUFFLE_PORT_CONFIG_KEY, DEFAULT_SHUFFLE_PORT);
  Channel ch = bootstrap.bind(new InetSocketAddress(port));
  accepted.add(ch);
  port = ((InetSocketAddress)ch.getLocalAddress()).getPort();
  conf.set(SHUFFLE_PORT_CONFIG_KEY, Integer.toString(port));
  pipelineFact.SHUFFLE.setPort(port);
  LOG.info(getName() + " listening on port " + port);
  super.serviceStart();

  sslFileBufferSize = conf.getInt(SUFFLE_SSL_FILE_BUFFER_SIZE_KEY,
                                  DEFAULT_SUFFLE_SSL_FILE_BUFFER_SIZE);
  connectionKeepAliveEnabled =
      conf.getBoolean(SHUFFLE_CONNECTION_KEEP_ALIVE_ENABLED,
        DEFAULT_SHUFFLE_CONNECTION_KEEP_ALIVE_ENABLED);
  connectionKeepAliveTimeOut =
      Math.max(1, conf.getInt(SHUFFLE_CONNECTION_KEEP_ALIVE_TIME_OUT,
        DEFAULT_SHUFFLE_CONNECTION_KEEP_ALIVE_TIME_OUT));
  mapOutputMetaInfoCacheSize =
      Math.max(1, conf.getInt(SHUFFLE_MAPOUTPUT_META_INFO_CACHE_SIZE,
        DEFAULT_SHUFFLE_MAPOUTPUT_META_INFO_CACHE_SIZE));
}
 
Example 6
Source File: NettyRev.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
public void startup(){
        try {
            bossExecutor = Executors.newCachedThreadPool();
            workerExecutor = Executors.newCachedThreadPool();
            bootstrap = new ServerBootstrap(
                    new NioServerSocketChannelFactory(
                            bossExecutor,workerExecutor));
            final NettyServerHandler nettyServerHandler = new NettyServerHandler();
            // 设置一个处理客户端消息和各种消息事件的类(Handler)
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                @Override
                public ChannelPipeline getPipeline() throws Exception {
                    ChannelPipeline pipeline = Channels.pipeline();
                    pipeline.addLast(
                            "decoder",
                            new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
                                    false, true, ChannelBuffers.copiedBuffer(
                                    delimiter,
                                    Charset.forName(encoding))));
                    pipeline.addLast("handler", nettyServerHandler);
                    return pipeline;
                }
            });
            bootstrap.setOption("child.receiveBufferSize", receiveBufferSize);
            bootstrap.setOption("child.keepAlive", true);
//            bootstrap.setOption("child.tcpNoDelay", true);
            bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host),
                    port));
            logger.warn("netty server start up success port:{}.", port);
        } catch (Exception e) {
            logger.error(e.getMessage());
            System.exit(1);
        }
    }
 
Example 7
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tell controller that we're ready to accept bgp peer connections.
 */
public void run() {

    try {

        peerBootstrap = createPeerBootStrap();

        peerBootstrap.setOption("reuseAddr", true);
        peerBootstrap.setOption("child.keepAlive", true);
        peerBootstrap.setOption("child.tcpNoDelay", true);
        peerBootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);

        final ServerBootstrap bootstrap = createServerBootStrap();

        bootstrap.setOption("reuseAddr", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);

        ChannelPipelineFactory pfact = new BgpPipelineFactory(bgpController, true);

        bootstrap.setPipelineFactory(pfact);
        InetSocketAddress sa = new InetSocketAddress(getBgpPortNum());
        cg = new DefaultChannelGroup();
        serverChannel = bootstrap.bind(sa);
        cg.add(serverChannel);
        log.info("Listening for Peer connection on {}", sa);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 8
Source File: Portmap.java    From big-c with Apache License 2.0 5 votes vote down vote up
void start(final int idleTimeMilliSeconds, final SocketAddress tcpAddress,
    final SocketAddress udpAddress) {

  tcpServer = new ServerBootstrap(new NioServerSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
  tcpServer.setPipelineFactory(new ChannelPipelineFactory() {
    private final HashedWheelTimer timer = new HashedWheelTimer();
    private final IdleStateHandler idleStateHandler = new IdleStateHandler(
        timer, 0, 0, idleTimeMilliSeconds, TimeUnit.MILLISECONDS);

    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(RpcUtil.constructRpcFrameDecoder(),
          RpcUtil.STAGE_RPC_MESSAGE_PARSER, idleStateHandler, handler,
          RpcUtil.STAGE_RPC_TCP_RESPONSE);
    }
  });

  udpServer = new ConnectionlessBootstrap(new NioDatagramChannelFactory(
      Executors.newCachedThreadPool()));

  udpServer.setPipeline(Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER,
      handler, RpcUtil.STAGE_RPC_UDP_RESPONSE));

  tcpChannel = tcpServer.bind(tcpAddress);
  udpChannel = udpServer.bind(udpAddress);
  allChannels.add(tcpChannel);
  allChannels.add(udpChannel);

  LOG.info("Portmap server started at tcp://" + tcpChannel.getLocalAddress()
      + ", udp://" + udpChannel.getLocalAddress());
}
 
Example 9
Source File: Main.java    From vmstats with Apache License 2.0 5 votes vote down vote up
public void run(Hashtable<String, String> appConfig) {
    ServerBootstrap bootstrap = new ServerBootstrap(
            new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));

    bootstrap.setPipelineFactory(new FakeCarbonPipelineFactory(appConfig));
    bootstrap.bind(new InetSocketAddress(port));
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("receiveBufferSize", 1048576);

}
 
Example 10
Source File: MemCacheDaemon.java    From fqueue with Apache License 2.0 5 votes vote down vote up
/**
 * Bind the network connection and start the network processing threads.
 */
public void start() {
	// TODO provide tweakable options here for passing in custom executors.
	channelFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors
			.newCachedThreadPool());

	allChannels = new DefaultChannelGroup("jmemcachedChannelGroup");

	ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);

	ChannelPipelineFactory pipelineFactory;
	if (binary)
		pipelineFactory = createMemcachedBinaryPipelineFactory(cache, memcachedVersion, verbose, idleTime,
				allChannels);
	else
		pipelineFactory = createMemcachedPipelineFactory(cache, memcachedVersion, verbose, idleTime, frameSize,
				allChannels);

	bootstrap.setOption("child.tcpNoDelay", true);
	bootstrap.setOption("child.keepAlive", true);
	bootstrap.setOption("child.receiveBufferSize", 1024 * 64);
	bootstrap.setPipelineFactory(pipelineFactory);

	Channel serverChannel = bootstrap.bind(addr);
	allChannels.add(serverChannel);

	log.info("Listening on " + String.valueOf(addr.getHostName()) + ":" + addr.getPort());

	running = true;
}
 
Example 11
Source File: WebSocketServer.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public void startServer() {
    if ( ( properties != null ) && ( Boolean
            .parseBoolean( properties.getProperty( "usergrid.websocket.disable", "false" ) ) ) ) {
        logger.info( "Usergrid WebSocket Server Disabled" );
        return;
    }

    logger.info( "Starting Usergrid WebSocket Server" );

    if ( realm != null ) {
        securityManager = new DefaultSecurityManager( realm );
    }

    ServerBootstrap bootstrap = new ServerBootstrap(
            new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool() ) );

    // Set up the pipeline factory.
    ExecutionHandler executionHandler =
            new ExecutionHandler( new OrderedMemoryAwareThreadPoolExecutor( 16, 1048576, 1048576 ) );

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(
            new WebSocketServerPipelineFactory( emf, smf, management, securityManager, executionHandler, ssl ) );

    // Bind and start to accept incoming connections.
    channel = bootstrap.bind( new InetSocketAddress( 8088 ) );

    logger.info( "Usergrid WebSocket Server started..." );
}
 
Example 12
Source File: FpmManager.java    From onos with Apache License 2.0 5 votes vote down vote up
private void startServer() {
    HashedWheelTimer timer = new HashedWheelTimer(
            groupedThreads("onos/fpm", "fpm-timer-%d", log));

    ChannelFactory channelFactory = new NioServerSocketChannelFactory(
            newCachedThreadPool(groupedThreads("onos/fpm", "sm-boss-%d", log)),
            newCachedThreadPool(groupedThreads("onos/fpm", "sm-worker-%d", log)));
    ChannelPipelineFactory pipelineFactory = () -> {
        // Allocate a new session per connection
        IdleStateHandler idleHandler =
                new IdleStateHandler(timer, IDLE_TIMEOUT_SECS, 0, 0);
        FpmSessionHandler fpmSessionHandler =
                new FpmSessionHandler(this, new InternalFpmListener());
        FpmFrameDecoder fpmFrameDecoder = new FpmFrameDecoder();

        // Setup the processing pipeline
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("FpmFrameDecoder", fpmFrameDecoder);
        pipeline.addLast("idle", idleHandler);
        pipeline.addLast("FpmSession", fpmSessionHandler);
        return pipeline;
    };

    InetSocketAddress listenAddress = new InetSocketAddress(FPM_PORT);

    serverBootstrap = new ServerBootstrap(channelFactory);
    serverBootstrap.setOption("child.reuseAddr", true);
    serverBootstrap.setOption("child.keepAlive", true);
    serverBootstrap.setOption("child.tcpNoDelay", true);
    serverBootstrap.setPipelineFactory(pipelineFactory);
    try {
        serverChannel = serverBootstrap.bind(listenAddress);
        allChannels.add(serverChannel);
    } catch (ChannelException e) {
        log.debug("Exception binding to FPM port {}: ",
                listenAddress.getPort(), e);
        stopServer();
    }
}
 
Example 13
Source File: CarbonPickleServer.java    From kairos-carbon with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws KairosDBException
{
	// Configure the server.
	m_serverBootstrap = new ServerBootstrap(
			new NioServerSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	// Configure the pipeline factory.
	m_serverBootstrap.setPipelineFactory(this);
	m_serverBootstrap.setOption("child.tcpNoDelay", true);
	m_serverBootstrap.setOption("child.keepAlive", true);
	m_serverBootstrap.setOption("reuseAddress", true);

	// Bind and start to accept incoming connections.
	m_serverBootstrap.bind(new InetSocketAddress(m_address, m_port));


	m_udpBootstrap = new ConnectionlessBootstrap(
			new NioDatagramChannelFactory());

	m_udpBootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(m_maxSize));

	m_udpBootstrap.setPipelineFactory(this);

	m_udpBootstrap.bind(new InetSocketAddress(m_port));

}
 
Example 14
Source File: HttpServer.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
public synchronized void run() {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    b.setPipelineFactory(new CommonHttpPipeline(TIMER));
    b.setOption("child.tcpNoDelay", true);
    channel = b.bind(new InetSocketAddress(port));
    LOG.info("server bound to port {}", port);
}
 
Example 15
Source File: TimestampServer.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public void startServer() {

        ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("TimestampServer-%d").setDaemon(true).build());
        this.factory = new NioServerSocketChannelFactory(executor, executor);

        SpliceLogUtils.info(LOG, "Timestamp Server starting (binding to port %s)...", port);

        ServerBootstrap bootstrap = new ServerBootstrap(factory);

        // If we end up needing to use one of the memory aware executors,
        // do so with code like this (leave commented out for reference).
        // But for now we can use the 'lite' implementation.
        //
        // final ThreadPoolExecutor pipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor(
        //     5 /* threads */, 1048576, 1073741824,
        //     100, TimeUnit.MILLISECONDS, // Default would have been 30 SECONDS
        //     Executors.defaultThreadFactory());
        // bootstrap.setPipelineFactory(new TimestampPipelineFactory(pipelineExecutor, handler));

        bootstrap.setPipelineFactory(new TimestampPipelineFactoryLite(handler));

        bootstrap.setOption("tcpNoDelay", true);
        // bootstrap.setOption("child.sendBufferSize", 1048576);
        // bootstrap.setOption("child.receiveBufferSize", 1048576);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.setOption("child.reuseAddress", true);
        // bootstrap.setOption("child.connectTimeoutMillis", 120000);

        this.channel = bootstrap.bind(new InetSocketAddress(getPortNumber()));

        SpliceLogUtils.info(LOG, "Timestamp Server started.");
    }
 
Example 16
Source File: MongoServer.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public void startServer() {

        if ( ( properties != null ) && ( Boolean
                .parseBoolean( properties.getProperty( "usergrid.mongo.disable", "false" ) ) ) ) {
            logger.info( "Usergrid Mongo Emulation Server Disabled" );
            return;
        }

        logger.info( "Starting Usergrid Mongo Emulation Server" );

        if ( realm != null ) {
            securityManager = new DefaultSecurityManager( realm );
        }

        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool() ) );

        bootstrap.setOption( "child.bufferFactory", HeapChannelBufferFactory.getInstance( ByteOrder.LITTLE_ENDIAN ) );

        // Set up the pipeline factory.
        ExecutionHandler executionHandler =
                new ExecutionHandler( new OrderedMemoryAwareThreadPoolExecutor( 16, 1048576, 1048576 ) );
        // TODO if config'ed for SSL, start the SslMSPF instead, change port as well?
        bootstrap.setPipelineFactory(
                new MongoServerPipelineFactory( emf, smf, management, securityManager, executionHandler ) );

        // Bind and start to accept incoming connections.
        channel = bootstrap.bind( new InetSocketAddress( 27017 ) );

        logger.info( "Usergrid Mongo API Emulation Server accepting connections..." );
    }
 
Example 17
Source File: BgpSessionManager.java    From onos with Apache License 2.0 5 votes vote down vote up
public void start() {
    log.debug("BGP Session Manager start.");
    isShutdown = false;

    ChannelFactory channelFactory = new NioServerSocketChannelFactory(
            newCachedThreadPool(groupedThreads("onos/bgp", "sm-boss-%d", log)),
            newCachedThreadPool(groupedThreads("onos/bgp", "sm-worker-%d", log)));
    ChannelPipelineFactory pipelineFactory = () -> {
        // Allocate a new session per connection
        BgpSession bgpSessionHandler =
                new BgpSession(BgpSessionManager.this);
        BgpFrameDecoder bgpFrameDecoder =
                new BgpFrameDecoder(bgpSessionHandler);

        // Setup the processing pipeline
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("BgpFrameDecoder", bgpFrameDecoder);
        pipeline.addLast("BgpSession", bgpSessionHandler);
        return pipeline;
    };
    InetSocketAddress listenAddress =
            new InetSocketAddress(bgpPort);

    serverBootstrap = new ServerBootstrap(channelFactory);
    // serverBootstrap.setOptions("reuseAddr", true);
    serverBootstrap.setOption("child.keepAlive", true);
    serverBootstrap.setOption("child.tcpNoDelay", true);
    serverBootstrap.setPipelineFactory(pipelineFactory);
    try {
        serverChannel = serverBootstrap.bind(listenAddress);
        allChannels.add(serverChannel);
    } catch (ChannelException e) {
        log.debug("Exception binding to BGP port {}: ",
                  listenAddress.getPort(), e);
    }
}
 
Example 18
Source File: NetworkFailuresProxy.java    From flink with Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

	// Set up the event pipeline factory.
	ClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(executor, executor);
	serverBootstrap.setOption("child.tcpNoDelay", true);
	serverBootstrap.setOption("child.keepAlive", true);
	serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();

			// synchronized for a race between blocking and creating new handlers
			synchronized (networkFailureHandlers) {
				NetworkFailureHandler failureHandler = new NetworkFailureHandler(
					blocked,
					networkFailureHandler -> networkFailureHandlers.remove(networkFailureHandler),
					channelFactory,
					remoteHost,
					remotePort);
				networkFailureHandlers.add(failureHandler);
				pipeline.addLast(NETWORK_FAILURE_HANDLER_NAME, failureHandler);
			}
			return pipeline;
		}
	});
	channel = serverBootstrap.bind(new InetSocketAddress(localPort));

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example 19
Source File: MemCacheDaemon.java    From fqueue with Apache License 2.0 5 votes vote down vote up
/**
 * Bind the network connection and start the network processing threads.
 */
public void start() {
	// TODO provide tweakable options here for passing in custom executors.
	channelFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors
			.newCachedThreadPool());

	allChannels = new DefaultChannelGroup("jmemcachedChannelGroup");

	ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);

	ChannelPipelineFactory pipelineFactory;
	if (binary)
		pipelineFactory = createMemcachedBinaryPipelineFactory(cache, memcachedVersion, verbose, idleTime,
				allChannels);
	else
		pipelineFactory = createMemcachedPipelineFactory(cache, memcachedVersion, verbose, idleTime, frameSize,
				allChannels);

	bootstrap.setOption("child.tcpNoDelay", true);
	bootstrap.setOption("child.keepAlive", true);
	bootstrap.setOption("child.receiveBufferSize", 1024 * 64);
	bootstrap.setPipelineFactory(pipelineFactory);

	Channel serverChannel = bootstrap.bind(addr);
	allChannels.add(serverChannel);

	log.info("Listening on " + String.valueOf(addr.getHostName()) + ":" + addr.getPort());

	running = true;
}
 
Example 20
Source File: RpcServerBootstrap.java    From voyage with Apache License 2.0 4 votes vote down vote up
private void initHttpBootstrap(int myport) {
	logger.info("initHttpBootstrap...........");
	final ServerConfig serverConfig = new ServerConfig(myport);
	final ChannelGroup channelGroup = new DefaultChannelGroup(getClass().getName());
	bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
			//建议用ThreadPoolExecutor代替
			Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool(), serverConfig.getThreadCnt()));
	//设置常见参数
	bootstrap.setOption("tcpNoDelay","true");//禁用nagle算法
	bootstrap.setOption("reuseAddress", "true");
	bootstrap.setOption("SO_RCVBUF",1024*128);
	bootstrap.setOption("SO_SNDBUF",1024*128);
	timer = new HashedWheelTimer();
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			int readTimeout = serverConfig.getReadTimeout();
			if (readTimeout > 0) {
				pipeline.addLast("timeout", new ReadTimeoutHandler(timer, readTimeout, TimeUnit.MILLISECONDS));
			}
			pipeline.addLast("decoder", new RpcRequestDecode());
			pipeline.addLast("encoder", new RpcResponseEncode());
			pipeline.addLast("handler", new NettyRpcServerHandler(channelGroup));
			return pipeline;
		}
	});
	
	int port = serverConfig.getPort();
	if (!checkPortConfig(port)) {
		throw new IllegalStateException("port: " + port + " already in use!");
	}

	Channel channel = bootstrap.bind(new InetSocketAddress(port));
	channelGroup.add(channel);
	logger.info("voyage server started");

	waitForShutdownCommand();
	ChannelGroupFuture future = channelGroup.close();
	future.awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	timer.stop();
	timer = null;

	logger.info("voyage server stoped");

}