The understanding of Netty and NiO is shallow, sharing some of the knowledge learned recently, the wrong place is also correct. Netty Introduction
Netty is an asynchronous Event-driven Network application framework
For rapid development of maintainable high performance protocol servers & clients.
Netty's official website says, presumably it means Netty is an asynchronous event-driven network application framework that can quickly develop maintainable high-performance network servers and client applications.
Asynchronous asynchronous, a large part of the Netty approach is asynchronous, and the event-driven model can handle more requests. The Netty consistency API has a high user experience compared to the JDK API.
It is also very convenient to use. Netty allows developers to focus more on business logic without having to consider too many underlying issues and various bugs.
Netty Status
This is Netty on GitHub's homepage Https://github.com/netty/netty, currently has 5000+ star
Many well-known companies and projects are using Netty, including large companies such as Facebook, IBM, Redhat, and Spark, Finagle, Nifty and other projects.
More adaptor in http://netty.io/wiki/adopters.html.
At present, the main maintenance version of Netty is 3.x, 4.x, 5.x. I touch more is 5.x, many frameworks are based on 3.x development, 3 4 5 There are some differences between
I think the new version was developed in the past experience and lessons, with the main 5.
Netty do something
Http://netty.io/images/components.png
Netty encapsulates the JDK's NIO, providing a consistent and good API for developers. Netty provides a lot of better "JDK API" implementations, such as its bytebuf.
What's the definition of fast?
Fast, I want to get a thing as soon as possible and I want to get all the things as soon as possible.
In Serverclient programming, the former can be considered as low latency, the lower delay, the completion of a request as soon as possible; While the latter is high throughput, larger system throughput.
Scalability Scalability
We need the system to be able to smoothly degrade performance when a large number of requests are being requested, and to get a corresponding performance boost when we upgrade our hardware configuration.
Server with different paradigm1. Single thread mode
Handle if you do not execute in a new thread then the while loop will block on handle processing and only one request can be processed at a time.
</pre>
2. Multithreaded executionA request corresponding to a thread, when the emergence of a large number of requests, thread creation, destruction, contextswitch overhead all back to affect system performance
ServerSocket serversocket = new ServerSocket (port), while (true) { socket socket = serversocket.accept (); New Thread () { @Override public void Run () { handle (socket); }
3. Thread poolThe thread pool does not solve the problem of a request-first-line, only limiting the cost of creating threads and controlling the creation of threads.
Executor Executor = executors.newfixedthreadpool (100); ServerSocket serversocket = new ServerSocket (port), while (true) { socket socket = serversocket.accept (); Executor.execute (New Runnable () { @Override public void Run () { handle (socket); } );}
4.JDK NIOConsider that the problem is on handle (socket), InputStream and OutputStream byte-based read and write, the read write operation is block operation, When no bytes can read or write, the execution thread will block.
Graph from "Netty in Action"
JDK1.4 provides NIO implementations, and NiO had two sayings at the time, new IO and non blocking IO, and now over the years, it's no longer new, and everyone calls it non blocking IO.
Some of the core Java.nio packages include buffer, the core of which is bytebuffer, whether the program interacts with the network layer or in the form of a byte stream. The Bytebuffer has both heap buffer and direct buffer (non heap buffer), and head buffer is in the Java heap,
Using a byte array as its internal data structure, direct buffer is outside the Java heap memory. There are two more important classes in the Java.nio.channels channel and selector, which represent a channel to a target that can read and write, the implementation class has FileChannel, Serversocketchannel, Socketchannel, etc., selector is used to register the event of interest in the channel, so that we can implement asynchronous Event-driven, implement a thread to handle multiple requests, multiplexing (multiplexing)
Serversocketchannel Serverchannel = Serversocketchannel.open (); Serverchannel.bind (new inetsocketaddress (port)); Serverchannel.configureblocking (FALSE); Selector Selector = Selector.open (); Serverchannel.register (Selector, selectionkey.op_accept); while (true) { Selector.select (); set<selectionkey> Selectionkeyset = Selector.selectedkeys (); iterator<selectionkey> Iterator = Selectionkeyset.iterator (); while (Iterator.hasnext ()) {Selectionkey Selectionkey = Iterator.next (); Iterator.remove (); if (selectionkey.isacceptable ()) {Serversocketchannel Server = (Serversocketchannel) selectionkey.channel (); Socketchannel client = Server.accept (); Client.configureblocking (FALSE); Client.register (Selector, selectionkey.op_read| Selectionkey.op_write, Bytebuffer.allocate (buffer_size)); } if (Selectionkey.isreadable ()) {Socketchannel client = (Socketchannel) selectionkey.channel (); Bytebuffer buf = (bytebuffer) SelectIonkey.attachment (); Client.read (BUF); } if (Selectionkey.iswritable ()) {Socketchannel client = (Socketchannel) selectionkey.channel (); Bytebuffer buf = (bytebuffer) selectionkey.attachment (); Buf.flip (); Client.write (BUF); Buf.compact (); } }}
This CPU usage is more serious
5. Netty NiOIn order to demonstrate the ability to put in a block. Netty Our byte parsing business implementation can be implemented with Channelhandler, Channelhandler series in channelpipeline form a kind of plug-in form, through the filter chain make each logic independent and reusable.
int port = 8090; Eventloopgroup Bossgroup = new Nioeventloopgroup (); Eventloopgroup Workergroup = new Nioeventloopgroup (); Serverbootstrap serverbootstrap = new Serverbootstrap () try{serverbootstrap.group (Bossgroup, WorkerGroup). Chan Nel (nioserversocketchannel.class). Childhandler (New channelinitializer<io.netty.channel.socket.socketchannel& gt; () {@Override protected void Initchannel (Io.netty.channel.socket.SocketChannel ch) throws Except Ion {Ch.pipeline (). AddLast ("Echohandler", new Channelhandleradapter () {@Override public void Channelreadcomplete (Channelhandlercontext ctx) throws Exception {Ctx.flush (); } @Override public void Channelread (Channelhandlercontext ctx, Object ms g) throws Exception {Ctx.write (msg); } @Override public void Exceptioncaught (ChAnnelhandlercontext CTX, Throwable cause) throws Exception {cause.printstacktrace (); Ctx.close (); } }); } }); Channelfuture f = serverbootstrap.bind (new inetsocketaddress (port)). sync (); F.channel (). Closefuture (). sync (); catch (Interruptedexception e) {e.printstacktrace ();} finally {bossgroup.shutdowngracefully (); Workergroup.shutdowngracefully ();}
Not to be continued ...
Continuning ...
More recommended information
Netty in action
http://g.oswego.edu/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Netty Development Notes