Netty
It is a high-performance, asynchronous event-driven NIO
framework that provides TCP
, UDP
support and file transfer. As the most popular NIO
framework Netty
in the field of Internet, big data distributed computing, game industry, communications industry, such as access to a wide range of applications, some of the industry's leading open source components is also based on Netty
the NIO
framework to build.
Netty
Take advantage of Java
the ability of advanced network, hiding the complexity behind it to provide an easy to use API
to build a client / server, which has a high concurrency, transmission faster, better packaging and so on.
High concurrencyNetty
is based on a NIO
( Nonblocking I/O
non-blocking IO
) network communications framework for the development, in contrast to the BIO
( Blocking I/O
blocking IO
), its concurrent performance has been greatly improved.
Fast transmissionNetty
of fast transmission is actually dependent on the NIO
one characteristic - zero copy .
Good packaging Netty NIO encapsulated many of the details of the operation, to provide easy to use API, as well as characteristics of heartbeat reconnection mechanism, stick package unpacking programs, enable developers to build a robust high concurrent applications quickly and efficiently.
Why Netty?
JDK
Native issues programNIO
JDK
Native also have a web application API
, but a series of problems, notably the following:
NIO
Libraries andAPI
complicated, cumbersome to use. You need to masterSelector
,ServerSocketChannel
,SocketChannel
,ByteBuffer
and so on.- Other need to have additional skills to pave the way. For example familiar with
Java
multi-threaded programming, because theNIO
program involves theReactor
mode, you have to multithreading and network programming is very familiar with, in order to write a high-qualityNIO
program. - Reliability capacity filled, the development workload and difficulty are very large. For example a client face reconnect disconnected, network glitches, half a pack reader, a cache failure, abnormal processing network congestion and so on stream.
NIO
Programming is characterized by functional development is relatively easy, but the reliability of the capacity filled workload and difficulty are very large. JDK NIO
ABug
. For example infamousEpoll Bug
, it will lead toSelector
empty polling, eventually leadingCPU 100%
. Officials say theJDK 1.6
versionupdate 18
fixes the problem, but untilJDK 1.7
version of the problem still exists, but theBug
probability of reducing some of it, it has not been fundamentally resolved occur.
Netty
specialty
Netty
To JDK
own NIO
the API
encapsulated solve the above problems, the main features are:
- Elegantly designed for the harmonization of transport types of
API
blocking and non-blockingSocket
; based on a flexible and extensible event model, clearly separating concerns; highly customizable threading model - a single thread, one or more thread pool; true connectionless datagram socket support (from3.1
starting). - Easy to use, a detailed record
Javadoc
, user guide and examples; no other dependencies,JDK 5
( )Netty 3.x
or6
( )Netty 4.x
is sufficient. - Performance, higher throughput, lower delay; reduce resource consumption; minimize unnecessary memory copying.
The safe, completeSSL/TLS
andStartTLS
support. - Community activists, constantly updated, community activists, short version iterations, found
Bug
can be repaired in time, at the same time, more new features will be added.
Netty internal execution flow
Server:
- Creating
ServerBootStrap
instances - Set and bind
Reactor
the thread pool:EventLoopGroup
,EventLoop
is registered to handle all of this threadSelector
aboveChannel
- Set and bind the service side
Channel
- Create a process network events
ChannelPipeline
andhandler
, in the form of network time in which the flow of the stream,handler
to complete the majority of the custom function: such as codecSSl
safety certification - Binding and start listening port
- When the rotational training to ready
channel
after byReactor
a thread:NioEventLoop
the implementationpipline
of the method, the final scheduling and executionchannelHandler
Client:
Netty architecture design
FIG main features are as follows:
Netty
Features are as follows:
- Transport service, support
BIO
andNIO
. - Container integration, support
OSGI
,JBossMC
,Spring
,Guice
container. - Protocol
HTTP
support ,Protobuf
binary, text,WebSocket
and a series of common protocols are supported. Also supports custom protocol implemented by executing coding and decoding logic. Core
Core, scalable event model, universal communicationAPI
, support for zero-copyByteBuf
buffer object.
Module assembly
Bootstrap
、ServerBootstrap
Bootstrap
The guide means is an Netty
application usually consists of a Bootstrap
start, the main role is to configure the entire Netty
program, the various components in series, Netty
the Bootstrap
classes are Class boot client program, ServerBootstrap
a boot server class.
Future
、ChannelFuture
As previously described, in Netty
all the IO
operations are asynchronous, not immediately know whether the message is processed correctly.
But after a while and so it can be completed or executed directly register a listener, specific implementation is through Future
and ChannelFutures
they can register a listener, when an operation success or failure of the monitoring will be triggered automatically registered to listen for events.
Channel
Netty
Components of the network communication can be used to perform network I/O
operations. Channel
To provide users with:
- The state of the current channel network connection (for example, whether to open? Are you connected?)
- Network configuration parameters for the connection (e.g., receive buffer size)
- It provides asynchronous network
I/O
operations (such as establishing a connection, read and write, to bind to port), an asynchronous call means that anyI/O
call will return immediately, and does not guarantee the end of the call to the requestedI/O
operation has been completed. Immediately return a callChannelFuture
instance, by registering listeners toChannelFuture
on, you canI/O
callback notification caller successful operation, cancel or fail. - Supporting the association
I/O
operation with a corresponding processing program.
Different protocols, different type of blocking has different connection Channel
types corresponding thereto. Here are some common Channel
types:
NioSocketChannel
Asynchronous clientTCP Socket
connections.NioServerSocketChannel
, Asynchronous serverTCP Socket
connection.NioDatagramChannel
, AsynchronousUDP
connection.NioSctpChannel
Asynchronous clientSctp
connections.NioSctpServerChannel
, AsynchronousSctp
server-side connection, which covers the channelsUDP
andTCP
the networkIO
and fileIO
.
Selector
Netty
Based on Selector
the object to achieve I/O
multiplexing through Selector
multiple connections you can listen to a thread Channel
event.
As to a Selector
registration Channel
, the Selector
internal mechanism can automatically continue to query ( Select
) of these registered Channel
whether there has been ready I/O
events (such as read, write, network connection is completed, etc.), so that the program can simply use a efficient management of multiple threads Channel
.
NioEventLoop
NioEventLoop
Maintained a thread and task queues, submit support asynchronous tasks will be called when the thread starts NioEventLoop
of run
methods to perform I/O
the task and non- I/O
task:
I/O
Tasks, namelyselectionKey
inready
the event, such asaccept
,connect
,read
,write
etc., by aprocessSelectedKeys
trigger method.- Non-
IO
task, added totaskQueue
the tasks, such asregister0
,bind0
and other tasks, therunAllTasks
trigger method.
Task execution time ratio of the two kinds of variableioRatio
control is default50
, it indicates a non-allowedIO
time and the task executionIO
is equal to the task execution time.
NioEventLoopGroup
NioEventLoopGroup
The main management eventLoop
life cycle, can be understood as a thread pool, to maintain a set of internal threads, each ( NioEventLoop
) is responsible for handling multiple Channel
events, and a Channel
corresponds to only one thread.
ChannelHandler
ChannelHandler
It is an interface to process I/O
an event or interception I/O
operation, and forwards it to its ChannelPipeline
(the processing chain) next handler.
ChannelHandler
Itself does not provide a lot of ways, because there are many ways this interface need to implement, during the easy to use, it can be inherited subclass:
ChannelInboundHandler
For processing inboundI/O
events.ChannelOutboundHandler
For processing outboundI/O
operations.
Or using the following adapter class:ChannelInboundHandlerAdapter
For processing inboundI/O
events.ChannelOutboundHandlerAdapter
For processing outboundI/O
operations.ChannelDuplexHandler
For inbound and outbound events.ChannelHandlerContext
SaveChannel
all relevant contextual information, as well as a relatedChannelHandler
object.
ChannelPipline
Preservation ChannelHandler
of List
, for processing or intercepting Channel
inbound and outbound event operation.
ChannelPipeline
Implements an advanced form of interception filter mode, the user has full control event handling, as well as Channel
in each of ChannelHandler
how they interact with each other.
Netty high-performance design
Netty
An asynchronous event-driven network, comes from its high performance of the I/O
model and the threading model, the former determines how receive data, which determines how data.
I / O model
What kind of channel to send data to each other BIO
, NIO
or AIO
, I/O
model largely determine the performance framework.
Blocking I / O
Traditional obstructive I/O
( BIO
) can be represented by the following figure:
The following characteristics and disadvantages:
- Each request requires a separate thread to complete data
Read
, business processes, dataWrite
integrity operational problems. - When a large number of concurrent need to create a large number of threads to handle connections, system resource consumption.
- After the connection is established, if the current thread is temporarily no data to read, the thread blocked in
Read
operation, resulting in waste of resources thread.
I / O multiplexing model in I/O
multiplexing model will be used Select
, this function will also make the process of blocking, and blocking but I/O
the difference is that this function can block multiple simultaneous I/O
operations.
But also simultaneously to a plurality of read operations, the write operation of a plurality of I/O
functions detected, until the data is read or written, it really calls the I/O
operating function.
Netty
Non-blocking I/O
Achieving key is based on the reuse model , used here represents an object:I/O
Selector
Netty
The IO
thread NioEventLoop
the polymerization of the multiplexer Selector
can handle hundreds of concurrent client connections.
When a thread from a client Socket
when read and write data channel, if no data is available, the thread can perform other tasks.
The threads are usually nonblocking IO
idle time for performing other channel IO
operation, the individual threads can manage a plurality of input and output channels.
Since the read and write operations are non-blocking, which can fully enhance IO
the efficiency of thread, avoid frequent I/O
clogging caused by thread suspension.
A I/O
thread can handle concurrent N
client connections and read and write operations, which solves the traditional synchronous blocking fundamentally I/O
a connection a thread model, architecture, performance, elastic scalability and reliability have been greatly improved.
Netty
Threading model
Netty
Mainly based on master-slave multithreaded model (see below) do some modification, wherein the master from a plurality of multi-threading models :Reactors
Reactor
Reactor
MainReactor
Responsible for the client's connection request, and the request is forwarded to SubReactor
. SubReactor
Is responsible for the corresponding channel IO
read and write requests. Non- IO
request (specifically logical processing) will be written directly to task queue waiting worker threads
for processing. The entire Doug Lee
Great God of Reactor
introduction: Scalable IO in Java
inside on a master-slave Reactor
view of a multi-threaded model: special note is: Although the Netty
threading model based on master-slave Reactor
multi-threaded, borrowed MainReactor
and SubReactor
structure. But the actual implementation SubReactor
and Worker
threads with a thread pool.
Netty
Zero copy
When data is sent, the traditional implementation is:
File.read(bytes);
Socket.send(bytes);复制代码
This embodiment requires four data and four copies of context switching:
- Data is read from the disk to the kernel
read buffer
- Data is copied from the kernel buffer to the user buffer
- Copy the data from the user to the kernel buffer
socket buffer
- The kernel data
socket buffer
copied to the network interface (hardware) buffer
The concept of zero-copy
Significantly above second and third steps is not necessary, by java
the FileChannel.transferTo
method to avoid the above two extra copies (of course, supported by the underlying operating system)
- Call
transferTo
, data from the fileDMA
copy engine to the kernelread buffer
- Then
DMA
from the kernelread buffer
copies the data to the network interfacebuffer
The above two operations do not need CPU
to participate, so I reached zero copy.
Netty
The zero copy is mainly reflected in three aspects:
bytebuffer
Netty
It is mainly used to send and receive messagesbytebuffer
,bytebuffer
using the external memory (DirectMemory
) directlySocket
read and write.Reason: Using traditional heap memory for
Socket
reading and writing,JVM
will heap memorybuffer
copy directly into memory and then written intosocket
, a plurality of buffer memory copy.DirectMemory
It can be sent directly to the card via the DMA interface.
Composite Buffers
Traditional
ByteBuffer
, if you need twoByteBuffer
combinations of data together, we need to first create asize=size1+size2
new array size, then copy the data into two arrays of the new array.However, the use of
Netty
a combination providedByteBuf
, you can avoid such an operation, becauseCompositeByteBuf
no real multipleBuffer
combined, but holds a reference to them, thus avoiding the copy of the data, to achieve a zero copy.
- For
FileChannel.transferTo
use
Netty
Used inFileChannel的transferTo
the method, the method relies on the operating system to realize zero copy.This article from the blog article multiple platforms OpenWrite release!
For more information, please click on my blog Mu Chen