package com.tokheim.aifueling.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Slf4j @Component public class NettyServer { @Autowired private NettyInitializer nettyInitializer; @Value("${nettyInfo.port}") private int port; @Value("${nettyInfo.boosThreadCount}") private int boosThreadCount; @Async public void start() { NioEventLoopGroup boosLoopGroup = new NioEventLoopGroup(boosThreadCount); NioEventLoopGroup workLoopGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boosLoopGroup, workLoopGroup) .channel(NioServerSocketChannel.class) .childHandler(nettyInitializer) .option(ChannelOption.SO_BACKLOG,1024) .childOption(ChannelOption.SO_KEEPALIVE,true); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); log.info("Server started on port {}", port); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); log.error(e.getMessage()); } finally { boosLoopGroup.shutdownGracefully(); workLoopGroup.shutdownGracefully(); } } }