Our own use of Java NIO to develop the network program is very cumbersome, netty for us to do everything, where Serverbootstrap is a startup helper class, understand it we can develop a simple NIO server program.
Do not understand the channel and handler in NIO, etc. can refer to the previous article
Learn Java Netty (i) –java NiO
serverbootstrap ():
//创建一个ServerBootstrap对象new ServerBootstrap;
Serverbootstrap has only one parameterless constructor, and the builder pattern is used here because there are too many arguments for serverbootstrap, and the builder pattern is a problem that requires multiple constructors to handle too many constructor arguments.
In simple terms:
When there are too many arguments, the constructors we write out may be
Serverbootstrap (int i);
Serverbootstrap (int i, double b);
Serverbootstrap (int i, double b, char c);
...
After using builder mode
Serverbootstrap (); There is only one parameterless constructor, and the rest of the parts that need to be built are written to the member function, so use it like this.
Serverbootstrap Server = Serverbootstrap ();
Server
. Construct1 ()
. Construct2 ()
. CONSTURCT3 ()
...
Of course it can.
Server.construct1 (). CONSTRUCT3 () ...
Which build we use, which is the builder mode
Builder Mode Disadvantages:
It is more complex to write and expensive to use, only for situations where there are too many constructor parameters.
Note Builder mode to return this
Serverbootstrap inherited from Abstractbootstrap
Take a look at the variables and methods inside the Serverbootstrap class
Public class serverbootstrap extends abstractbootstrap<serverbootstrap , serverchannel>{ //Log errors such as exception logs, using the Java Reflection Mechanism and Factory mode Private Static FinalInternallogger logger = internalloggerfactory.getinstance (Serverbootstrap.class);//netty4.0 introduces a new type named Channeloption, which provides type-safe access to the socket option. Channeloption class Internal socket socket configuration parameters, such as SO_KEEPALIVE,SO_RECVBUF, etc. Private FinalMap<channeloption<?>, object> childoptions =NewLinkedhashmap<channeloption<?>, object> ();//Properties of the entity Private FinalMap<attributekey<?>, object> childattrs =NewLinkedhashmap<attributekey<?>, object> ();//Event loop, and bind thread pool Private volatileEventloopgroup Childgroup;//handling of channel handler Private volatileChannelhandler Childhandler;//Method //Only one event loop body to accept and process IO PublicServerbootstrapGroup(Eventloopgroup group);//There are two event loop bodies, one to accept the request, and the other to handle the clinet IO PublicServerbootstrapGroup(Eventloopgroup Parentgroup, Eventloopgroup childgroup);//Set channel properties Public<T> Serverbootstrapchildoption(channeloption<t> childoption, T value);//Set the channel that matches the given attribute Public<T> Serverbootstrapchildattr(attributekey<t> Childkey, T value);//child processing of channel handler PublicServerbootstrapChildhandler(Channelhandler Childhandler);//return Childgroup PublicEventloopgroupChildgroup();//Initialize and configure a number of parameters voidInit (Channel Channel)throwsException PublicServerbootstrapValidate();
There are some less important methods are not listed above, there are some methods from the parent class Abstractbootstrap, the code is too long to paste, interested can go to git to see the source
Abstractbootstrap.java
However, the parameters and interfaces from the Serverbootstrap startup helper class and Serverbootstrap class can be seen as serverbootstrap primarily used to configure the service side. The complex service-side configuration is accomplished with just one object serverbootstrap, which simplifies our programming a lot.
look at an example:
Public class echoserver { Private Final intPort Public Echoserver(intPort) { This. Port = port; } Public void Run()throwsexception{Eventloopgroup Bossgroup =NewNioeventloopgroup (); Eventloopgroup Workergroup =NewNioeventloopgroup ();Try{//Create a serverbootstrap, start configuration belowServerbootstrap B =NewServerbootstrap ();///created two eventloopgroup (thread pool and selector,reactor model) A main loop A child loop is combined by Serverboootstrap's group method //Then pass the option method to the server-side nioserversocketchannel (service-side socket) to set its backlog parameters. //The handler to set the processing event of the service-side socket (Serversocketchannel) via handler is the logging logger ///Last Childhandler setting up each socket connected to the server (Socketchannel) handler (Childhandler), is to create a Echoserverhandler class to handle. (using Channelhandler We can complete the function customization) //channelpipeline is responsible for managing and executing Channelhandler, which can be added to channelpipeline add Channelhandler //(Note serverbootstrap Partial method from parent class)B.group (Bossgroup, Workergroup). Channel (nioserversocketchannel.class). Option (Chann Eloption.so_backlog, -). Handler (NewLogginghandler (Loglevel.info)). Childhandler (NewChannelinitializer<socketchannel> () { Public void Initchannel(Socketchannel ch)throwsException {the handler in//abstractbooststrap is a factory class that creates a new handler for each newly accessed client . //The code below will create a echoserverhandler for each new socketSystem.out.println ("Hello"); Ch.pipeline (). AddLast (NewEchoserverhandler ());//ch.pipeline (). AddLast (New Logginghandler (Loglevel.info));} });//Bind port, all IO operations in Netty are asynchronous, it returns immediately, but does not guarantee complete operationChannelfuture f = b.bind (port). sync (); System.out.println ("bind ...."); F.channel (). Closefuture (). sync (); }Catch(Exception e) {E.printstacktrace (); }finally{bossgroup.shutdowngracefully (); Workergroup.shutdowngracefully (); } } Public Static void Main(string[] args)throwsException {intPortif(Args.length >0) {port = Integer.parseint (args[0]); }Else{Port =10000; }NewEchoserver (Port). Run (); }}
The above just a line of code to complete a lot of parameter settings, for our programming to simplify a lot.
Serverbootstrap Creating a Time series diagram:
Pictures not Original
Supplemental Factory mode:
The Factory mode uses the reflection of Java, the parameter is Class<> We pass the parameters to. Class (the type of the object building) instead of the class object instance, and then build the corresponding object in the method as needed, which also delays the creation of the object, which is simply what type of item we need to tell the factory that the factory produces to our corresponding entity.
Meaning of parameters such as backlog
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Learn Java Netty (ii)--Serverbootstrap