Netty is a network framework for Java NIO, which masks the underlying network details and is highly efficient. If you're recently developing a messaging platform, it's best to use Netty.
A good message platform has many details to be aware of and the agreed guidelines to follow. The graceful closure of the platform is essential. This is primarily to avoid message loss. So how do netty gracefully close it.
In Netty, there are two thread executor Bossexecutor and workerexecutor for accepting connection requests and processing requests, and shutting down channel is required in addition to shutting down the two.
The Netty document says graceful shutdown takes three steps:
1. All channel created by Unbind Netty. Channel.unbind ()
2. All channel created by close Netty. Channel.close ()
3. Shutdown Netty Thread executor. Factory.releaseexternalresources ()
For Netty generated channel, you can use Channelgroup management, very convenient.
The specific code is as follows: (see Channelgroup's comments)
Channelgroup allchannels = new Defaultchannelgroup ();
public static void Main (string[] args) throws Exception {
Serverbootstrap b = new Serverbootstrap (..);
...
Start the server
b.getpipeline (). AddLast ("handler", New MyHandler ());
Channel Serverchannel = B.bind (..);
Allchannels.add (Serverchannel);
... Wait until the shutdown signal reception ...
Close the Serverchannel and then all accepted connections.
Allchannels.close (). awaituninterruptibly ();
B.releaseexternalresources ();
}
The public class MyHandler extends Simplechannelupstreamhandler {@Override the public
void Channelopen ( Channelhandlercontext CTX, channelstateevent e) {
//ADD all open channels to the global group so that they are
Closed on shutdown.
Allchannels.add (E.getchannel ());
}