Netty thread model [next]

tags: Netty  java  Development language  rear end

  • Hey everyone, I amJava small white 2021
  • The programmer of the halfway is in the development of aircraft, and the opportunity to find a more interesting thing under the development of a surveying court, and stepped into the programmed world ... PS: At the same time, it is also a car that loves to travel. expert!
  • Purpose: Record your own learning history, I hope you can help you, please refer to you! Learn exchange together

Model explanation

  1. Netty abstract two sets of thread pools BossGroup and WorkerGroup, BossGroup is responsible for receiving client connections, and WorkerGroup is responsible for reading and writing of networks.
  2. BossGroup and Workergroup types are nioeventloopgroup.
  3. NioEventLoopGroup is equivalent to an event cycleThread groupThis group contains multiple event loop threads, each event loop thread is nioeventloop.
  4. Each nioeventloop has a Selector for listening to the network communication registered on SocketChannel.
  5. Steps per boss nioeventloop thread execution steps are 3 steps
    • Processing the Accept event, establish a connection with the Client, generate NiosocketChannel
    • Register NiosocketChannel to Selector on a WORKER NIOEVENTLOOP
    • Handling the task of the task queue, ie RunAllTasks
  6. Steps per worker nioeventloop thread Perform step
    • Polling registered all Niosocketchannel on your own Selector's Read, Write events
    • Processing I / O events, ie Read, Write events, in correspondence NiosocketChannel processing services
    • RunAllTasks handles tasks for task queue TaskQueue, some time-consuming business processing can generally be processed in TaskQueue, which does not affect the flow of data in pipeline
  7. When each Worker NioEventLoop processes the NiosocketChannel service, you will use the PIPELINE, and the PIPELINE maintains a lot of Handler processors to process data in Channel.

Module component

Bootstrap、ServerBootstrap

Bootstrap means booting, a Netty application is usually starting by a bootstrap, the main function is to configure the entire Netty program, in series, the BootStrap class in Netty is the boot boot class of the client program, ServerBootstrap is the service-enable boot class

Future、ChannelFuture

All IO operations in Netty are asynchronous and cannot beware of whether the message is properly processed.
But you can wait for a while to perform or directly register a monitored, the specific time is through Future and ChannelFutures, which can be registered with a monitor, and the listener will automatically trigger the registration monitoring event when the operation is performed.

Channel

Netty network communication components can be used to perform network I / O operations. Channel provides users:

  • The status of the channel current network connection (is open? Is it connected, etc.)
  • Configuration parameters for network connections (receiving buffer size)
  • Provide asynchronous network I / O operation (establishment of connection, reading, binding port), asynchronous call means that any I / O call will return immediately, and does not guarantee the I / O operation of the autumn in the end of the call. .
  • Call now returns a CHANNELFUTURE instance, by registering the listener to CHANELFUTURE, you can operate successfully, fail, or cancel the callback notification call.
  • Support the associated I / O operation and the corresponding procedure. Different protocols, different blocked types of links have different CHANNEL types and corresponding.

Here are some common Channel types:

NiosocketChannel, asynchronous client TCP Socket connection.
NioserversocketChannel, asynchronous server-side TCP Socket connection.
NiodatagramChannel, asynchronous UDP connection.
NiosctPChannel, asynchronous client SCTP connection.
NiosCTPServerChannel, asynchronous SCTP server-side connection.
These channels covers UDP and TCP network IOs and file IO.

Selector

Netty is based on the Selector object to implement I / O multi-channel reuse, and you can listen to multiple connected Channel events through Selector. When you register with the Channel in a Selector, the mechanism within Selector can automatically query if these registered Channel has a ready I / O event (eg readable, writable, network connection completion, etc.), so The program can easily manage multiple Channel using a thread.

NioEventLoop

A thread and task queue is maintained in NiOEventLoop, support asynchronous submission execution tasks, and the thread is started to call the NiOEventLoop RUN method, perform I / O tasks and non-I / O tasks:
I / O mission, Ready events in SelectionKey, such as Accept, Connect, Read, Write, etc., triggered by ProcessSelectedKeys method
Non-I / O tasks, add to tasks in TaskQueue, such as register0, bind0 and other tasks, triggered by RunalLTasks method

NioEventLoopGroup

NiOEventLoopGroup, mainly manages EventLoop lifecycle, which can be understood as a thread pool, which maintains a set of threads, each thread (nioeventloop) responsible for handling multiple Channel, and a Channel only corresponds to a thread.

ChannelHandler

ChannelHandler is an interface, processing I / O events, or blocking I / O operations, forwarding it to the next handler in its CHANNELPIPELINE.
ChannelHandler itself does not provide many ways, because this interface has many methods need to be realized, and can inherit its subclasses during the trial

ChannelInBoundHandler is used to process an inbound I / O event.
ChannelOutBoundHandler is used to process outbound I / O operations.

Or use the following adapter classes

ChannelInBoundHandleRadapter is used to process an inbound I / O event.
ChannelOutBoundHandleRadapter is used to process outbound I / O operations.

ChannelHandlerContext

Save all Context information related to Channel while managing the ChannelHandler object.

ChannelPipeline

Save ChannelHandler's List for handling or intercepting the incoming events of Channel and outbound operations.
ChannelPipeline implements a high-grade intercept filter mode that allows users to fully control the processing method of the event, and how the ChannelHandler in Channel interacts with each other.
Each Channel in Netty has only one channelpipeline corresponding, and their compositional relationships are as follows


A Channel contains a CHANNELPIPELINE, while ChannelPipeline has maintained a two-way linked list consisting of ChannelHandlerContext, and a ChannelHandler is associated with each ChannelHandlerContext.

Read events (inbound events) and WRITE events (outbound events) In a two-way linked list, inbound events are passed from the list of HEADs to the last inbound handler, and outbound events will pass from the list TAIL to The one-stop Handler, two types of Handler interfere with each other.

ByteBuf

From the structure, Bytebuf is constructed from a string byte array. Each byte in the array is used to store information.

Bytebuf provides two indexes, one for reading data, one for writing data. By moving in the byte array, these two indexes are positioned to locate the location where read or write information.

When read from bytebuf, its ReaderIndex will increase based on the number of bytes read.

Similarly, when writing Bytebuf, its WriterIndex will also increase according to the number of bytes written.

It should be noted that the limit is that readerIndex just reads the WriterIndex written.

When ReaderIndex exceeds WriterIndex, Netty will throw indexOutofboundsexception.

Sample code:

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

public class NettyByteBuf {
    public static void main(String[] args) {
        // Create a BYTEBUF object, the inside of the object contains a byte array byte [10]
        // divide Buffer into three areas via ReaderIndex and WriterIndex and Capacity
        // The area that has been read: [0, ReaderIndex)
        // Readable area: [ReaderIndex, WriterIndex)
        // Well-writable area: [WriterIndex, Capacity)
        ByteBuf byteBuf = Unpooled.buffer(10);
        System.out.println("byteBuf=" + byteBuf);

        for (int i = 0; i < 8; i++) {
            byteBuf.writeByte(i);
        }
        System.out.println("byteBuf=" + byteBuf);

        for (int i = 0; i < 5; i++) {
            System.out.println(byteBuf.getByte(i));
        }
        System.out.println("byteBuf=" + byteBuf);

        for (int i = 0; i < 5; i++) {
            System.out.println(byteBuf.readByte());
        }
        System.out.println("byteBuf=" + byteBuf);


        // Create bytebuf with UNPOOLED Tool Class
        ByteBuf byteBuf2 = Unpooled.copiedBuffer("hello,xiaobai2021!", CharsetUtil.UTF_8);
        // use related methods
        if (byteBuf2.hasArray()) {
            byte[] content = byteBuf2.array();
            // convert content into string
            System.out.println(new String(content, CharsetUtil.UTF_8));
            System.out.println("byteBuf2=" + byteBuf2);

            System.out.println(byteBuf2.getByte(0)); / / Get the ASCII code of the character H of the array 0, H = 104

            int len = byteBuf2.readableBytes(); // Readable bytes 12
            System.out.println("len=" + len);

            // Use for to remove each byte
            for (int i = 0; i < len; i++) {
                System.out.println((char) byteBuf2.getByte(i));
            }

            // Range Read
            System.out.println(byteBuf2.getCharSequence(0, 6, CharsetUtil.UTF_8));
            System.out.println(byteBuf2.getCharSequence(6, 6, CharsetUtil.UTF_8));
        }
    }
}

Intelligent Recommendation

Thread model in Netty

The core concept in Netty isEvent loop (EventLoop), Which is actually Reactor in Reactor mode,Responsible for monitoring network events and calling event handlers for processing.In the 4.x version of ...

Netty features and thread model

Zero copy hard driver - kernel buffer - protocol engine only DMA copy avoids cpu copy There was actually a cpu copy of kernel buffer - socket buffer, but the copied information can rarely be ignored; ...

013. NETTY thread model

Introduction to Netty Netty is a high-performance, high-scalable asynchronous event-driven network application framework, which greatly simplifies network programming such as TCP and UDP clients and s...

Netty thread model and basics

Why use Netty Netty is an asynchronous event-driven web application framework for rapid development of maintainable high-performance and high-profile servers and clients. Netty has the advantages of h...

Netty thread model and gameplay

Event cycle group   All I / O operations in Netty are asynchronous, and the asynchronous execution results are obtained by channelfuture. Asynchronously executes a thread pool EventLoopGroup, it ...

More Recommendation

Netty - Thread Model Reactor

table of Contents Thread model 1, traditional IO service model 2, Reactor mode reactor Three modes: to sum up Netty model Excommissum Thread model 1, traditional IO service model Blocked IO mode Get i...

【Netty】 thread model

content 1. Single Reactor single thread 2. Single Reactor Multi -thread 3. Reactor Main Strike Model Single -threaded model (single Reactor single thread) Multi -threaded model (single Reactor multi -...

Netty entry thread model

Single-threaded model: the boss thread is responsible for connection and data reading and writing Hybrid model: the boss thread is responsible for connection and data reading and writing, and the work...

Redis source code parsing: 09redis database implementations (key operation, key timeout function key space notification)

This chapter of the Redis database server implementations are introduced, indicating achieve Redis database-related operations, including key-value pairs in the database to add, delete, view, update a...

PAT B1041-B1045 Question

1、b1041 2、b1042 3、b1043 4、b1044 5、b1045...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top