Preliminary understanding of Netty

Source: Internet
Author: User

 PackageCom.hhr.demo;ImportIo.netty.bootstrap.ServerBootstrap;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInitializer;ImportIo.netty.channel.ChannelPipeline;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.SimpleChannelInboundHandler;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.channel.socket.nio.NioServerSocketChannel;ImportIo.netty.handler.codec.http.DefaultFullHttpResponse;ImportIo.netty.handler.codec.http.FullHttpResponse;ImportIo.netty.handler.codec.http.HttpHeaderNames;Importio.netty.handler.codec.http.HttpRequest;ImportIo.netty.handler.codec.http.HttpResponseStatus;ImportIo.netty.handler.codec.http.HttpServerCodec;Importio.netty.handler.codec.http.HttpVersion;ImportIo.netty.util.CharsetUtil;//@SpringBootApplication Public classdemo1application { Public Static voidMain (string[] args)throwsException {//Springapplication.run (Demo1application.class, args);                /**         * Define the Eventloopgroup, define the bootstrap (Serverbootstrap) and the type of channel used (generally niosocketchannel, * server is Nioserversock         Etchannel), the remainder is business-related, using Channelinitializer and specific handler.         * Mainly 2+n (N is a custom number of handler) classes. * To better understand and further netty, let's take a general look at the components used by Netty and how they work together throughout the Netty architecture. Essential components in the Netty application: Bootstrap or serverbootstrap eventloop eventloopgroup Channel             Pipeline Channel Future or Channelfuture Channelinitializer Channelhandler             Bootstrap, a Netty application is usually started by a Bootstrap, and its main function is to configure the entire Netty program, in tandem with each component. Handler, the Handler component was born to support various protocols and the way data is processed.             Handler is mainly used to handle various events, where events are widespread, such as connectivity, data reception, anomalies, data conversion, etc. Channelinboundhandler, one of the most commonly used handler.             The function of this handler is to handle the event of receiving data, that is to say, our business logic is generally written in this handler, Channelinboundhandler is used to deal with our core business logic. Channelinitializer, when a link is established, we need to know how to receive or send the data, of course, we have a variety of handler implementations to deal with it, then Channelinitializer is used to configure these handler, It will provide a channelpipeline and add handler to ChaNnelpipeline.             Channelpipeline, a Netty application is based on the channelpipeline mechanism, which relies on eventloop and eventloopgroup because all three of them are related to event or event handling.             The purpose of Eventloops is to handle IO operations for channel, and a eventloop can serve multiple channel.             Eventloopgroup will contain multiple eventloop.             The channel represents a socket link, or other component related to IO operations, which is used with eventloop to participate in IO processing. In the future, all IO operations in Netty are asynchronous, so you can't immediately know if the message is handled correctly, but we can wait for it to execute or register a listener directly, and the implementation is through the future and Channelfutures, They can register a listener and the listener will automatically trigger when the operation succeeds or fails.          In summary, all operations will return a channelfuture.*/Eventloopgroup Bossgroup=NewNioeventloopgroup (2); Eventloopgroup Workergroup=NewNioeventloopgroup (4);//The first Eventloopgroup is specifically responsible for binding to the Port Listener connection event, while the second eventloopgroup is used to handle each received connection            /*** 1, if you do not specify the number of threads, the number of threads is: CPU number of cores * 2, depending on whether the number of threads is a power of 2, with different policies initialized Chooser                                3. Nthreads Nioeventloop objects are saved in the children array. It can be understood that Nioeventloop is a thread, and there are several properties in the thread Nioeventloop: 1, Nioeventloopgroup (in the parent class Singlethreadevente                                Xecutor) 2, selector 3, provider 4, Thread (in the parent class Singlethreadeventexecutor) More popular point is: Nioeventloopgroup is a thread pool, Nioeventloop is A thread.             There are n nioeventloop threads in the nioeventloopgroup thread pool. */Serverbootstrap Serverbootstrap=NewServerbootstrap (); Try {                /*** 1, Group:workergroup is saved on the Childgroup property of the Serverbootstrap object. Bossgroup objects that are stored on the group property of the Serverbootstrap object 2, Channelfactory:bootstrapchannelfactory class (The Clazz property is: nioservers                                        Ocketchannel.class) 3, Handler:simpleserverhandler 4, Childhandler*/Serverbootstrap.group (Bossgroup, Workergroup)/*** The function of this line of code is to generate an instance of the Nioserversocketchannel class by reflection, where this Nioserversocketchannel class object has several properties: * Socketchannel, Nioserversocketchannelconfig, selectionkey.op_accept events, Niomessageunsafe, DefaultChannelPipel INE*/. Channel (Nioserversocketchannel.class)//When a connection arrives, Netty registers a channel, and then Eventloopgroup assigns a eventloop bound to the channel, during the entire life cycle of the channel, will be served by the eventloop that binds to it, and this eventloop is a thread. Childhandler (NewMychannelinitializer ()); Channelfuture Future= Serverbootstrap.bind (8999). sync ();            Future.channel (). Closefuture (). sync (); } finally{bossgroup.shutdowngracefully ();            Workergroup.shutdowngracefully (); }    }}classMychannelinitializerextendsChannelinitializer<socketchannel>{@Overrideprotected voidInitchannel (Socketchannel ch)throwsException {//pipeline adds a Channelinitializer object, which overrides the Initchannel method. This method adds a serverbootstrapacceptor to the Serverchannel pipeline processor through P.addlast () .//As you can see from the name, this is an access device that specifically accepts new requests and throws new requests to an event loop .Channelpipeline pipeline =ch.pipeline ();//Pipeline.addlast (New Httprequestdecoder ());//Pipeline.addlast (New Httpresponseencoder ());        /*** Since multiple Nioeventloop,next method callbacks are maintained in Nioeventloopgroup, the Chooser policy is used to find the next nioeventloop, and the Register method of executing the object is registered. */Pipeline.addlast ("Httpservercodec",NewHttpservercodec ()); System.out.println ("---------------------"); Pipeline.addlast (NewMyhttphandler ()); }}/*** Netty with the use of the codec class is more convenient.    Pipeline.addlast ("Httpservercodec", New Httpservercodec ()); The simplest way to implement your own handler is to use Simplechannelinboundhandler to receive the HttpRequest method class Myhttphandler extends        Simplechannelinboundhandler*/classMyhttphandlerextendsSimplechannelinboundhandler{@Overrideprotected voidChannelRead0 (Channelhandlercontext ctx, HttpRequest msg)throwsException {System.out.println ("*********************************************************");        System.out.println (Msg.getclass ());        System.out.println (Msg.uri ());        System.out.println (Msg.method (). name ());        System.out.println (Ctx.channel (). remoteaddress ()); System.out.println ("Headers:");        Msg.headers (). ForEach (System.out::p rintln); Bytebuf buf= Unpooled.copiedbuffer ("Hello World", Charsetutil.utf_8); Fullhttpresponse Response=Newdefaultfullhttpresponse (httpversion.http_1_1, Httpresponsestatus.ok, buf); Response.headers (). Set (Httpheadernames.content_type,"Text/plain");        Response.headers (). Set (Httpheadernames.content_length, Buf.readablebytes ()); Ctx.writeandflush (response);//Ctx.channel (). Close ();    }    /*** Processing WebSocket request # only need to add a websocketserverprotocolhandler on the basis above, complete as follows: Pipeline.addlast ("Httpservercod    EC ", New Httpservercodec ());    Pipeline.addlast (New Chunkedwritehandler ());    Pipeline.addlast (New Httpobjectaggregator (8096));           Pipeline.addlast (New Websocketserverprotocolhandler ("/ws"));     Its own processor can receive and process Websocketframe subclasses. */     }

Preliminary understanding of Netty

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.