springboot整合netty优雅关闭netty(未企业实战)

@SpringBootApplication
public class SpringbootNettyApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootNettyApplication.class, args);
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
//            此处必须加,否则可能直接退出(也可使用addListener方法)
//            channelFuture.channel().closeFuture().sync();
            Runtime.getRuntime().addShutdownHook(new Thread(() ->
            {
                System.out.println("ShutdownHook execute start...");
                System.out.println("Netty NioEventLoopGroup shutdownGracefully...");
                try {
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println("Netty NioEventLoopGroup shutdownGracefully2...");
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("ShutdownHook execute end...");
            }, "Allen-thread"));
//            或者使用此方式
            channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {

//                    此处写业务逻辑处理代码,当执行  bossGroup.shutdownGracefully();、workerGroup.shutdownGracefully();会调用改方法
                    System.out.println("我被他们(kill)给弄死了");
                    TimeUnit.SECONDS.sleep(3);
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {



        }

    }

}

测试

使用ctrl + c ,linux环境使用kill pid,不能使用强制关闭

你可能感兴趣的:(Netty)