use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project BRFS by zhangnianli.
the class NettyHttpServer method start.
@Override
public void start() throws InterruptedException {
ServerBootstrap serverStart = new ServerBootstrap();
serverStart.group(bossGroup, workerGroup);
serverStart.channel(NioServerSocketChannel.class);
serverStart.childHandler(handlerInitializer);
// 积压数量
serverStart.option(ChannelOption.SO_BACKLOG, baklog);
// 连接超时时间(毫秒)
serverStart.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conTimeout);
// 保持连接
serverStart.childOption(ChannelOption.SO_KEEPALIVE, true);
InetSocketAddress address = (ip == null ? new InetSocketAddress(port) : new InetSocketAddress(ip, port));
channelFuture = serverStart.bind(address).sync();
}
use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project swift by luastar.
the class RpcServer method start.
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
pipeline.addLast(new RpcDecoder(RpcRequest.class, rpcSerialize));
pipeline.addLast(new RpcEncoder(RpcResponse.class, rpcSerialize));
pipeline.addLast(new RpcServerChannelHandler(handlerMap));
}
});
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
Channel channel = bootstrap.bind(port).sync().channel();
logger.info("SwiftRpcServer started on port {}", port);
// 注册 RPC 服务地址
String serviceAddress = RpcConstant.CURRENT_SERVER_ADDRESS + ":" + port;
for (String interfaceName : handlerMap.keySet()) {
serviceRegistry.register(interfaceName, serviceAddress);
}
channel.closeFuture().sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project CorfuDB by CorfuDB.
the class CorfuServer method main.
public static void main(String[] args) {
serverRunning = true;
// Parse the options given, using docopt.
Map<String, Object> opts = new Docopt(USAGE).withVersion(GitRepositoryState.getRepositoryState().describe).parse(args);
int port = Integer.parseInt((String) opts.get("<port>"));
// Print a nice welcome message.
AnsiConsole.systemInstall();
printLogo();
System.out.println(ansi().a("Welcome to ").fg(RED).a("CORFU ").fg(MAGENTA).a("SERVER").reset());
System.out.println(ansi().a("Version ").a(Version.getVersionString()).a(" (").fg(BLUE).a(GitRepositoryState.getRepositoryState().commitIdAbbrev).reset().a(")"));
System.out.println(ansi().a("Serving on port ").fg(WHITE).a(port).reset());
System.out.println(ansi().a("Service directory: ").fg(WHITE).a((Boolean) opts.get("--memory") ? "MEMORY mode" : opts.get("--log-path")).reset());
// Pick the correct logging level before outputting error messages.
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
switch((String) opts.get("--log-level")) {
case "ERROR":
root.setLevel(Level.ERROR);
break;
case "WARN":
root.setLevel(Level.WARN);
break;
case "INFO":
root.setLevel(Level.INFO);
break;
case "DEBUG":
root.setLevel(Level.DEBUG);
break;
case "TRACE":
root.setLevel(Level.TRACE);
break;
default:
root.setLevel(Level.INFO);
log.warn("Level {} not recognized, defaulting to level INFO", opts.get("--log-level"));
}
log.debug("Started with arguments: " + opts);
// Create the service directory if it does not exist.
if (!(Boolean) opts.get("--memory")) {
File serviceDir = new File((String) opts.get("--log-path"));
if (!serviceDir.exists()) {
if (serviceDir.mkdirs()) {
log.info("Created new service directory at {}.", serviceDir);
}
} else if (!serviceDir.isDirectory()) {
log.error("Service directory {} does not point to a directory. Aborting.", serviceDir);
throw new RuntimeException("Service directory must be a directory!");
}
}
// Now, we start the Netty router, and have it route to the correct port.
router = new NettyServerRouter(opts);
// Create a common Server Context for all servers to access.
serverContext = new ServerContext(opts, router);
// Add each role to the router.
addSequencer();
addLayoutServer();
addLogUnit();
addManagementServer();
router.baseServer.setOptionsMap(opts);
// Setup SSL if needed
Boolean tlsEnabled = (Boolean) opts.get("--enable-tls");
Boolean tlsMutualAuthEnabled = (Boolean) opts.get("--enable-tls-mutual-auth");
if (tlsEnabled) {
// Get the TLS cipher suites to enable
String ciphs = (String) opts.get("--tls-ciphers");
if (ciphs != null) {
List<String> ciphers = Pattern.compile(",").splitAsStream(ciphs).map(String::trim).collect(Collectors.toList());
enabledTlsCipherSuites = ciphers.toArray(new String[ciphers.size()]);
}
// Get the TLS protocols to enable
String protos = (String) opts.get("--tls-protocols");
if (protos != null) {
List<String> protocols = Pattern.compile(",").splitAsStream(protos).map(String::trim).collect(Collectors.toList());
enabledTlsProtocols = protocols.toArray(new String[protocols.size()]);
}
try {
sslContext = TlsUtils.enableTls(TlsUtils.SslContextType.SERVER_CONTEXT, (String) opts.get("--keystore"), e -> {
log.error("Could not load keys from the key store.");
System.exit(1);
}, (String) opts.get("--keystore-password-file"), e -> {
log.error("Could not read the key store password file.");
System.exit(1);
}, (String) opts.get("--truststore"), e -> {
log.error("Could not load keys from the trust store.");
System.exit(1);
}, (String) opts.get("--truststore-password-file"), e -> {
log.error("Could not read the trust store password file.");
System.exit(1);
});
} catch (Exception ex) {
log.error("Could not build the SSL context");
System.exit(1);
}
}
Boolean saslPlainTextAuth = (Boolean) opts.get("--enable-sasl-plain-text-auth");
// Create the event loops responsible for servicing inbound messages.
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
EventExecutorGroup ee;
bossGroup = new NioEventLoopGroup(1, new ThreadFactory() {
final AtomicInteger threadNum = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("accept-" + threadNum.getAndIncrement());
return t;
}
});
workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {
final AtomicInteger threadNum = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("io-" + threadNum.getAndIncrement());
return t;
}
});
ee = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {
final AtomicInteger threadNum = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("event-" + threadNum.getAndIncrement());
return t;
}
});
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(io.netty.channel.socket.SocketChannel ch) throws Exception {
if (tlsEnabled) {
SSLEngine engine = sslContext.newEngine(ch.alloc());
engine.setEnabledCipherSuites(enabledTlsCipherSuites);
engine.setEnabledProtocols(enabledTlsProtocols);
if (tlsMutualAuthEnabled) {
engine.setNeedClientAuth(true);
}
ch.pipeline().addLast("ssl", new SslHandler(engine));
}
ch.pipeline().addLast(new LengthFieldPrepender(4));
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
if (saslPlainTextAuth) {
ch.pipeline().addLast("sasl/plain-text", new PlainTextSaslNettyServer());
}
ch.pipeline().addLast(ee, new NettyCorfuMessageDecoder());
ch.pipeline().addLast(ee, new NettyCorfuMessageEncoder());
ch.pipeline().addLast(ee, router);
}
});
ChannelFuture f = b.bind(port).sync();
while (true) {
try {
f.channel().closeFuture().sync();
} catch (InterruptedException ie) {
}
}
} catch (InterruptedException ie) {
} catch (Exception ex) {
log.error("Corfu server shut down unexpectedly due to exception", ex);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project dubbo by alibaba.
the class NettyServer method doOpen.
@Override
protected void doOpen() throws Throwable {
NettyHelper.setNettyLoggerFactory();
bootstrap = new ServerBootstrap();
bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), new DefaultThreadFactory("NettyServerWorker", true));
final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
channels = nettyServerHandler.getChannels();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE).childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
// .addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder()).addLast("handler", nettyServerHandler);
}
});
// bind
ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
channelFuture.syncUninterruptibly();
channel = channelFuture.channel();
}
use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project geode by apache.
the class GeodeRedisServer method startRedisServer.
/**
* Helper method to start the server listening for connections. The server is bound to the port
* specified by {@link GeodeRedisServer#serverPort}
*
* @throws IOException
* @throws InterruptedException
*/
private void startRedisServer() throws IOException, InterruptedException {
ThreadFactory selectorThreadFactory = new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("GeodeRedisServer-SelectorThread-" + counter.incrementAndGet());
t.setDaemon(true);
return t;
}
};
ThreadFactory workerThreadFactory = new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("GeodeRedisServer-WorkerThread-" + counter.incrementAndGet());
return t;
}
};
bossGroup = null;
workerGroup = null;
Class<? extends ServerChannel> socketClass = null;
if (singleThreadPerConnection) {
bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory);
workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory);
socketClass = OioServerSocketChannel.class;
} else {
bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory);
workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory);
socketClass = NioServerSocketChannel.class;
}
InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
String pwd = system.getConfig().getRedisPassword();
final byte[] pwdB = Coder.stringToBytes(pwd);
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (logger.fineEnabled())
logger.fine("GeodeRedisServer-Connection established with " + ch.remoteAddress());
ChannelPipeline p = ch.pipeline();
p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder());
p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GeodeRedisServer.this, pwdB));
}
}).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GeodeRedisServer.connectTimeoutMillis).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync();
if (this.logger.infoEnabled()) {
String logMessage = "GeodeRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads;
if (this.singleThreadPerConnection)
logMessage += ", One worker thread per connection";
else
logMessage += ", Worker threads: " + this.numWorkerThreads;
this.logger.info(logMessage);
}
this.serverChannel = f.channel();
}
Aggregations