Netty gracefully off

Source: Internet
Author: User

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

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.