use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project riposte by Nike-Inc.
the class Server method startup.
public void startup() throws CertificateException, IOException, InterruptedException {
if (startedUp) {
throw new IllegalArgumentException("This Server instance has already started. " + "You can only call startup() once");
}
// Figure out what port to bind to.
int port = Integer.parseInt(System.getProperty("endpointsPort", serverConfig.isEndpointsUseSsl() ? String.valueOf(serverConfig.endpointsSslPort()) : String.valueOf(serverConfig.endpointsPort())));
// Configure SSL if desired.
final SslContext sslCtx;
if (serverConfig.isEndpointsUseSsl()) {
sslCtx = serverConfig.createSslContext();
} else {
sslCtx = null;
}
// Configure the server
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
Class<? extends ServerChannel> channelClass;
// NIO event loop group.
if (Epoll.isAvailable()) {
logger.info("The epoll native transport is available. Using epoll instead of NIO. " + "riposte_server_using_native_epoll_transport=true");
bossGroup = (serverConfig.bossThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numBossThreads()) : new EpollEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
workerGroup = (serverConfig.workerThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numWorkerThreads()) : new EpollEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
channelClass = EpollServerSocketChannel.class;
} else {
logger.info("The epoll native transport is NOT available or you are not running on a compatible " + "OS/architecture. Using NIO. riposte_server_using_native_epoll_transport=false");
bossGroup = (serverConfig.bossThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numBossThreads()) : new NioEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
workerGroup = (serverConfig.workerThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numWorkerThreads()) : new NioEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
channelClass = NioServerSocketChannel.class;
}
eventLoopGroups.add(bossGroup);
eventLoopGroups.add(workerGroup);
// Figure out which channel initializer should set up the channel pipelines for new channels.
ChannelInitializer<SocketChannel> channelInitializer = serverConfig.customChannelInitializer();
if (channelInitializer == null) {
// No custom channel initializer, so use the default
channelInitializer = new HttpChannelInitializer(sslCtx, serverConfig.maxRequestSizeInBytes(), serverConfig.appEndpoints(), serverConfig.requestAndResponseFilters(), serverConfig.longRunningTaskExecutor(), serverConfig.riposteErrorHandler(), serverConfig.riposteUnhandledErrorHandler(), serverConfig.requestContentValidationService(), serverConfig.defaultRequestContentDeserializer(), new ResponseSender(serverConfig.defaultResponseContentSerializer(), serverConfig.errorResponseBodySerializer()), serverConfig.metricsListener(), serverConfig.defaultCompletableFutureTimeoutInMillisForNonblockingEndpoints(), serverConfig.accessLogger(), serverConfig.pipelineCreateHooks(), serverConfig.requestSecurityValidator(), serverConfig.workerChannelIdleTimeoutMillis(), serverConfig.proxyRouterConnectTimeoutMillis(), serverConfig.incompleteHttpCallTimeoutMillis(), serverConfig.maxOpenIncomingServerChannels(), serverConfig.isDebugChannelLifecycleLoggingEnabled(), serverConfig.userIdHeaderKeys(), serverConfig.responseCompressionThresholdBytes(), serverConfig.httpRequestDecoderConfig());
}
// Create the server bootstrap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(channelClass).childHandler(channelInitializer);
// execute pre startup hooks
if (serverConfig.preServerStartupHooks() != null) {
for (PreServerStartupHook hook : serverConfig.preServerStartupHooks()) {
hook.executePreServerStartupHook(b);
}
}
if (serverConfig.isDebugChannelLifecycleLoggingEnabled())
b.handler(new LoggingHandler(SERVER_BOSS_CHANNEL_DEBUG_LOGGER_NAME, LogLevel.DEBUG));
// Bind the server to the desired port and start it up so it is ready to receive requests
Channel ch = b.bind(port).sync().channel();
// execute post startup hooks
if (serverConfig.postServerStartupHooks() != null) {
for (PostServerStartupHook hook : serverConfig.postServerStartupHooks()) {
hook.executePostServerStartupHook(serverConfig, ch);
}
}
channels.add(ch);
logger.info("Server channel open and accepting " + (serverConfig.isEndpointsUseSsl() ? "https" : "http") + " requests on port " + port);
startedUp = true;
// Add a shutdown hook so we can gracefully stop the server when the JVM is going down
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
shutdown();
} catch (Exception e) {
logger.warn("Error shutting down Riposte", e);
}
}
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project pravega by pravega.
the class ConnectionFactoryImplTest method setUp.
@Before
public void setUp() throws Exception {
// Configure SSL.
port = TestUtils.getAvailableListenPort();
final SslContext sslCtx;
if (ssl) {
try {
sslCtx = SslContextBuilder.forServer(new File("../config/cert.pem"), new File("../config/key.pem")).build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
} else {
sslCtx = null;
}
boolean nio = false;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
try {
bossGroup = new EpollEventLoopGroup(1);
workerGroup = new EpollEventLoopGroup();
} catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
nio = true;
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
}
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler handler = sslCtx.newHandler(ch.alloc());
SSLEngine sslEngine = handler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
sslEngine.setSSLParameters(sslParameters);
p.addLast(handler);
}
}
});
// Start the server.
serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project summer by foxsugar.
the class SocketServer method start.
private void start() throws Exception {
ServerConfig serverConfig = SpringUtil.getBean(ServerConfig.class);
int port = serverConfig.getPort();
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
} else {
sslCtx = null;
}
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SocketServerInitializer(sslCtx));
// Start the server.
ChannelFuture f = b.bind(port).sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project web3sdk by FISCO-BCOS.
the class ChannelConnections method startListen.
public void startListen(Integer port) {
if (running) {
logger.debug("服务已启动");
return;
}
logger.debug("初始化connections listen");
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
final ChannelConnections selfService = this;
final ThreadPoolTaskExecutor selfThreadPool = threadPool;
try {
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource keystoreResource = resolver.getResource(getClientKeystorePath());
Resource caResource = resolver.getResource(getCaCertPath());
ks.load(keystoreResource.getInputStream(), getKeystorePassWord().toCharArray());
/*
* 每次连接使用新的handler
* 连接信息从socketChannel中获取
*/
ChannelHandler handler = new ChannelHandler();
handler.setConnections(selfService);
handler.setIsServer(true);
handler.setThreadPool(selfThreadPool);
SslContext sslCtx = SslContextBuilder.forServer((PrivateKey) ks.getKey("client", getClientCertPassWord().toCharArray()), (X509Certificate) ks.getCertificate("client")).trustManager(caResource.getFile()).build();
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
}
});
ChannelFuture future = serverBootstrap.bind(port);
future.get();
running = true;
} catch (Exception e) {
logger.error("系统错误", e);
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project baseio by generallycloud.
the class NettyClientThread method main.
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new HelloClient());
}
});
System.out.println("################## Test start ####################");
ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
System.out.println(f.isSuccess());
Channel channel = f.channel();
System.out.println("channel is active :" + channel.isActive() + ",channel:" + channel);
int len = 1024 * 64;
StringBuilder s = new StringBuilder(len);
for (int i = 0; i < len; i++) {
s.append(len % 10);
}
final String msg = s.toString();
ThreadUtil.execute(new Runnable() {
@Override
public void run() {
int i = 0;
for (; ; ) {
// String s = "hello Service! ---> :" + i;
ChannelFuture f = channel.writeAndFlush(msg);
ThreadUtil.sleep(1);
System.out.println(f.isDone() + "--------" + i);
i++;
}
}
});
ThreadUtil.sleep(Integer.MAX_VALUE);
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
Aggregations