Netty elegantly closed

Source: Internet
Author: User

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 useChannelGroupManagement, 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());     } }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.