Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| @Component public class NettyServer {
private Logger logger = LoggerFactory.getLogger(getClass());
@Value("${netty.port}") private Integer port;
@Resource private NettyServerHandlerInitializer nettyServerHandlerInitializer;
private EventLoopGroup bossGroup = new NioEventLoopGroup(); private EventLoopGroup workerGroup = new NioEventLoopGroup(); private Channel channel;
@PostConstruct public void start() throws InterruptedException { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .option(ChannelOption.SO_BACKLOG, 1024) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.TCP_NODELAY, true) .childHandler(nettyServerHandlerInitializer); ChannelFuture future = bootstrap.bind().sync(); if (future.isSuccess()) { channel = future.channel(); logger.info("[start][Netty Server 启动在 {} 端口]", port); } }
@PreDestroy public void shutdown() { if (channel != null) { channel.close(); } bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }
}
|
NettyServerHandlerInitializer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| @Component public class NettyServerHandlerInitializer extends ChannelInitializer<Channel> {
private static final Integer READ_TIMEOUT_SECONDS = 3 * 60; @Resource private NettyServerHandler nettyServerHandler;
@Override protected void initChannel(Channel ch) { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline .addLast(new ReadTimeoutHandler(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)) .addLast(new InvocationEncoder()) .addLast(new InvocationDecoder()) .addLast(messageDispatcher) .addLast(nettyServerHandler) ; }
}
|