项目中准备用 netty 做些定制化的功能,自然而然用上了 SpringBoot 这套,招不在老管用就好。思路就是不启动 tomcat ,在主线程启动 netty 。
public static void main(String[] args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start("start app...");
ConfigurableApplicationContext context = SpringApplication.run(NettyServer.class, args);
//get bean
SecondHandler handler = context.getBean(SecondHandler.class);
int port = context.getEnvironment().getProperty("server.port", Integer.class, 9000);
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(16);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline()
.addLast("codec", new HttpServerCodec())
.addLast("compressor", new HttpContentCompressor())
.addLast("aggregator", new HttpObjectAggregator(65536))
.addLast("handler", handler);
}
})
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind().sync();
stopWatch.stop();
log.info("Netty Server started ,Listening on {}, info={}", port, stopWatch.prettyPrint());
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}