Netty is a Java NiO network framework that shields the underlying network details and is very efficient. If you are developing a messaging platform recently, it is best to use netty.
A good messaging platform has many details that need attention and the agreed principles that should be followed. The elegant shutdown of the platform is essential. This is mainly to avoid message loss. So how can we achieve netty's elegant shutdown?
In netty, there are two thread executors, bossexecutor and workerexecutor, respectively, for accepting connection requests and processing requests. In addition to closing these two executors, you also need to disable the channel.
According to the netty document, it takes three steps to gracefully close the service:
1. All channels created by unbind netty. Channel. Unbind ()
2. Close all channels created by netty. Channel. Close ()
3. shutdown the netty thread executor. Factory.releaseExternalResources()
For channels generated by netty, you can useChannelGroup
Management, very convenient.
The specific code is as follows: (SeeChannelGroup
)
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(); } public class MyHandler extends SimpleChannelUpstreamHandler { @Override 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()); } }