首先是配置文件,加入netty自定义相关配置
netty:
server:
port: 10011
bossGroupNum: 2
workerGroupNum: 6
代码加载相关配置,将NettyServer交给spring容器去管理。
这里的关键是实现了CommandLineRunner接口
这样 NettyServer在加载实例化的时候就会执行重写的run方法,这样就能执行启动netty相关代码
@Component
public class NettyServer implements CommandLineRunner {
@Value("${netty.server.port}")
private int port;
@Value("${netty.server.bossGroupNum}")
private int bossGroupNum;
@Value("${netty.server.workerGroupNum}")
private int workerGroupNum;
@Autowired
private ServerChannelInitializer serverChannelInitializer;
private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
public void run() throws InterruptedException {
NioEventLoopGroup boss = new NioEventLoopGroup(bossGroupNum);
NioEventLoopGroup worker = new NioEventLoopGroup(workerGroupNum);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss,worker)
.channel(NioServerSocketChannel.class)
.childHandler(serverChannelInitializer)
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture sync = serverBootstrap.bind(port).sync();
logger.info("NettyServer Started on "+port+"...");
// 等待服务器 socket 关闭 。
sync.channel().closeFuture().sync();
}finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
@Override
public void run(String... args) throws Exception {
run();
}
@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> implements InitializingBean {
@Autowired
private ApplicationContext applicationContext;
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//根据具体业务添加相关解析类,这里不再详细说明
}
}
启动项目看到控制台打印出 NettyServer Started on 就说明启动成功了