Hello, today for everyone to share Netty, quickly take out a small book to write it down!

Introduction to Netty

Netty is an asynchronous event-driven network application framework for rapid development of maintainable high-performance protocol servers and clients.

Why use Netty

2.1 disadvantages of handwritten Java NIO

Because writing Java NIO yourself is cumbersome:

1) NIO class library and API complex, to master Selector, ServerSocketChannel, SocketChannel, ByteBuffer and so on

2) Be familiar with Java multithreaded programming involving the Reactor model in order to write high quality NIO programs

3) The infamous epoll bug, which causes the selector to poll empty and ultimately causes the CPU to be 100%.

2.2. Advantages of Netty

1) API is simple to use and low cost to learn

2) Many functions are packaged, such as encoding and decoding, supporting multiple protocols such as PB

3) High performance: Compared with other NIO frameworks, NetTY has the best performance

4) Active community

5) Dubbo, ES, RocketMQ, GRPC and so on have adopted Netty, and their quality has been verified.

3. Netty architecture diagram

The diagram above shows the structure of netty’s official website homepage:

1) The green part is Core Core module, including zero copy, API library, extensible event model, etc

2) Orange part: Protocol support, including HTTP Protocol, webSocket, SSL, Protocol Buffer, Zlib /gzip compression and decompression, Large File Transfer, etc.

3) The red part represents the transmission service, including Socket, Datagram, Http Tunnel, etc

From the diagram above, you can see what Netty has: its features, protocols, transport mode support are relatively complete.

4. Use Netty

4.1. Introduce Maven dependencies

Ty < groupId > io.net < / groupId > < artifactId > netty -all < / artifactId > < version > 4.1.20. The Final < / version >Copy the code

4.2 create a server startup class

4.3. Create a server service processor Handler

4.4. Create a client startup class

4.5. Create a client service processor Handler

5. Netty features and key components

5.1. TaskQueue taskQueue

If the Handler Handler has some long processing time, it can be sent to the taskQueue asynchronously.

Summary: This explains the problem in the reactor: After the handler listens to the workGroup event, it actually puts it into the taskQueue thread pool for asynchronous processing.

5.2. ScheduleTaskQueue Indicates the queue of delayed tasks

Deferred task queues, in addition to handler handling asynchrony, just wait a little longer before executing:

ctx.channel().eventLoop().schedule(new Runnable() {

@override public void run() {try {// The Handler does not block thread.sleep (1000); System.out.println(" long service processing "); } catch (Exception e) { e.printStackTrace(); }}Copy the code

},5, TimeUnit.SECONDS); // Execute after 5 seconds

5.3 Future asynchrony

When the client starts, there is this line of code:

// Connect to the server

ChannelFuture = bootstrap.connect("127.0.0.1", 6666).sync();Copy the code

ChannelFuture provides an asynchronous notification method when an operation is complete. In Socket programming, responses are blocked, and ChannelFuture returns results asynchronously in observer mode:

5.4 Bootstrap and ServerBootStrap

Bootstrap and ServerBootStrep are netty’s factory classes for creating client and server boosters. Using this factory class makes it very easy to create boot classes:

To create an initiator using Bootstrap, perform the following steps

5.4.1, group ()

In the Reactor Pattern article, we learned that the server uses two thread groups:

1) bossGroup: used to listen for client connections and is responsible for creating a connection with the client and registering the connection with the Selector of the WorkGroup

2) workGroup: used to process read and write events for each connection

Create threads using the following new:

EventLoopGroup bossGroup = new NioEventLoopGroup();

EventLoopGroup workerGroup = new NioEventLoopGroup();

So, since this is a thread group, what is the default number of threads? See the source code:

As can be seen from the source code, the default number of threads is 2 times the number of CPU cores. If you want to customize the number of threads, you can use the parameter constructor:

// Set the number of bossGroup threads to 1

EventLoopGroup bossGroup = new NioEventLoopGroup(1);

// Set the number of workerGroup threads to 16

EventLoopGroup workerGroup = new NioEventLoopGroup(16); v

5.4.2, channel ()

The channel() method is used to set the channel type. When a connection is established, the corresponding channel instance is created based on this setting:

There are the following types of channels:

1) NioSocketChannel: asynchronous non-blocking client TCP Socket connection

2) NioServerSocketChannel: asynchronous non-blocking server TCP Socket connection

Note: These two channel types are commonly used because they are asynchronous and non-blocking

3) OioSocketChannel: synchronizes blocked client TCP Socket connections

4) OioServerSocketChannel: synchronizes blocked server TCP Socket connections

5.4.3 Option() and childOption()

1. Option () : Sets the connection the server uses to receive the incoming connection, namely the bossGroup thread

2. ChildOption () : is the connection provided to the parent pipe, i.e. the bossWork thread

The SocketChannel argument, which is the usual argument for childOption() :

SO_RCVBUF Socket specifies the size of the TCP data receiving buffer.

TCP_NODELAY TCP parameter: sends data immediately. The default value is true.

The SO_KEEPALIVE Socket parameter is used to keep the connection alive. The default value is False. When this function is enabled, TCP proactively detects the validity of idle connections.

The ServerSocketChannel parameter, also known as the option() parameter: the queue length of the boss thread pool

The SO_BACKLOG Socket parameter indicates the length of the queue for the server to accept connections. If the queue is full, the client connection will be rejected. The default value is 200 for Windows and 128 for others.

5.4.4 Setting up assembly line (key)

The ChannelPipeline is the responsibility chain of the Netty to process the request, and the ChannelHander is the processor to process the request. Each channel actually has a pipeline of processors.

Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen