Http-Netty-Rpc-Service System Transformation: Do not block the start of the main thread springboot, init method nettyserver of postconstruct annotated Do not write future.channel () closeFuture () sync ();..

Conventional demo level netty server-side code is written like this:

the try {
                 // create and initialize the object Netty server starting aid ServerBootstrap 
                ServerBootstrap ServerBootstrap = RpcServer. the this .initServerBootstrap (bossGroup, workerGroup);
                 // Bind the corresponding ip and port, sync wait for success 
                ChannelFuture Future = serverBootstrap.bind (Port). Sync (); 
                logger.info ( "RPC Server is started, the port: {}" , port);
                 // wait for the server listening port closed 
                .. future.channel () closeFuture () Sync (); 
            } the catch (InterruptedException I ) { 
                LOGGER.error ( "rpc server exception occurs, the port: {}, the cause is:"  , port, i.getMessage ());
            } The finally {
                 // elegant exit, release NIO thread group 
                workerGroup.shutdownGracefully (); 
                bossGroup.shutdownGracefully (); 
            }

In it future.channel () closeFuture () sync ();.. The main purpose of this statement is easy to test, easy to write a non-springboot the demo, such as a simple junit test method, closeFuture () sync (). can prevent junit test server will shut down and stop test application time does not need to manually shut down the server and then call the method workerGroup.shutdownGracefully () .... Such peace of mind at the time of the test design.

However, when the nettyserver link to start springboot applications such nettyserver set @Component, when springboot scanned nettyserver, springboot main thread execution method postconstruct to nettyserver comments, and then happened

. future.channel () closeFuture () sync ();.
This results in springboot main thread blocked and can not continue to load the rest of the bean,
Worse, if springboot also added springboot-web dependent (comes with tomcat container) , it will be blocked and unable to start tomcat servlet engine webapplicationcontext.

Can not be simply constructed in a method of nettyserver / init process write future.channel () closeFuture () sync ();.. And workerGroup.shutdownGracefully ().

Just in the constructor / init method bootstrap.bind (port), which is asynchronous and does not block the main thread springboot.

The stop method and separately extracted.

Note that, even though the application directly off springboot, not manually stop calling the above method, nettyserver will be released before the port binding, to be safe, you can add annotations stop method @predestroy

 




Guess you like

Origin www.cnblogs.com/CreatorKou/p/11606870.html