项目中准备用 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();
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.