package com.zy.gateway.pipeline; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.ResourceLeakDetector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * 输送设备网关引导类 * Created by vincent on 2020-06-04 */ @Component public class PipelineBootstrap implements Bootstrap { private static Logger log = LoggerFactory.getLogger(PipelineBootstrap.class); private Channel channel; private ServerBootstrap bootstrap; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; @Autowired private PipelineProperties pipelineProperties; @Autowired private HandlerInitializer handlerInitializer; { bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); } /** * 网关启动初始化 */ @Override @PostConstruct public void serverStart() throws Exception { bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(handlerInitializer) .option(ChannelOption.SO_BACKLOG, pipelineProperties.getBacklog()) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.SO_KEEPALIVE, pipelineProperties.isKeepAlive()) .childOption(ChannelOption.SO_SNDBUF, pipelineProperties.getSndbuf()) .childOption(ChannelOption.SO_RCVBUF, pipelineProperties.getRcvbuf()); ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED); log.info("TCP server started successfully, port:{}", pipelineProperties.getTcpPort()); channel = bootstrap.bind(pipelineProperties.getTcpPort()).sync().channel(); } @Override @PreDestroy public void destroy() { if (channel != null && channel.isActive()) { channel.close(); } if (bossGroup != null) { bossGroup.shutdownGracefully(); } if (workerGroup != null) { workerGroup.shutdownGracefully(); } log.info("TCP server stopped successfully, port: {}", pipelineProperties.getTcpPort()); } }