Chapter One: Netty Introduction

Source: Internet
Author: User
Tags jboss

1. Netty Introduction

Netty is an asynchronous event-driven network application framework that enables rapid development of maintainable , High-performance, protocol-oriented servers and clients . Netty is based on NIO, so the entire netty is asynchronous , and Web applications often require a high degree of scalability, whether Netty or other Java NIO-based frameworks, providing a scalable solution.

2. Why use Netty?

Netty is one of the industry's most popular NIO frameworks, and its robustness, functionality, performance, customisation, and scalability are among the best in its kind, and it has been validated by hundreds of commercial projects, such as the RPC framework for Hadoop, and Avro uses Netty as the underlying communication framework. Many other industry-leading RPC frameworks also use Netty to build high-performance asynchronous communication capabilities.
Through the analysis of Netty, we summarize its advantages as follows:
1) easy to use API;
2) Powerful, preset a variety of codec functions, support a variety of mainstream protocols;
3) Strong customization ability, the communication framework can be flexibly expanded through Channelhandler;
4) High performance, through the comparison with other industry mainstream NIO framework, Netty of the comprehensive energy optimization;
5) Mature, stable, netty fixed all of the JDK NiO bugs that have been found, and business developers don't need to worry about nio bugs anymore;
3. Netty is very versatile

The package structure of Netty is as follows

in this case, channel and the handler two parts are more complex. We may as well compare it with the official Netty structure to understand its function.

    • zero-copy-capable Rich Byte buffer 0 copy of buffer. Why is it called 0 copies? Because at the time of data transmission, the final processing of the data will require a single transport layer of the message, the combination or split. NiO native Bytebuffer To do this, a copy of the Bytebuffer content is required to generate a new bytebuffer, and Netty achieves 0 copies by providing composite (combination) and slice (slicing) of the two buffer. This part of the code is in the org.jboss.netty.buffer package.
    • Universal Communication API Unified Communication API. Because of Java's old I/O and new I/O, incompatible APIs are used, and Netty provides a unified API ( org.jboss.netty.channel.Channel ) to encapsulate both I/O models. This part of the code is in the org.jboss.netty.channel package.

4. Summary of Netty characteristics

category

netty Properties

design

Unified API, supports multiple transport types, A simple and powerful threading model for blocking and non-blocking true non-connected datagram sockets support link logic components to support multiplexing

Easy to use

performance

have more than Java Core API higher throughput and lower latency thanks to pooling and reuse, with lower resource consumption with minimal memory replication

robustness

OutOfMemoryError eliminates the unfair read/write ratios common to NIO applications in high-speed networks due to slow, fast, or overloaded connections

Security

Complete SSL/TLS and STARTTLS support can be used in restricted environments such as applets and OSGi

Community driven

publish fast and frequent

5. Core components of Netty

main component blocks of the Netty:

    • Channel
    • Callback
    • Future
    • Events and ChannelHandler .

These building blocks represent different types of constructs: resources, logic, and notifications . Your application will use them to access the network and the data that flows through the network.

For each component, we will provide a basic definition and, where appropriate, a simple sample code to illustrate its use.

5.1 Channel

Channel is a basic construct of Java NIO. It represents an open connection to an entity (such as a hardware device, a file, a network socket, or a program component capable of performing one or more different I/O operations), such as read operations and write operations, which can now be Channel regarded as vectors of incoming (inbound) or outgoing (outbound) data. Therefore, it can be opened or closed, connected or disconnected.

5.2 Callback

A callback is actually a method that points to a reference to a method that has been supplied to another method. This allows the latter to invoke the former at the appropriate time. Callbacks are used in a wide range of programming scenarios and are one of the most common ways to notify stakeholders when the operation is complete.

Netty uses callbacks internally to handle events, and when a callback is triggered, the associated event can be handled by an interface-ChannelHandler implementation.

The Code listing 1-2 shows an example:

1) When a new connection has been established, ChannelHandler the channelActive() callback method will be called and a message will be printed.

2) triggered by a callbackChannelHandler

 Public class extends channelinboundhandleradapter {    @Override    publicvoid  channelactive ( Channelhandlercontext ctx)        throws Exception {    -- when a new connection has been established, channelactive ( Channelhandlercontext) will be called        System.out.println (            "Client" + Ctx.channel (). Remoteaddress () + " Connected ");}    }
5.3 Future

1) The future provides another way to notify the application when the operation is complete. This object can be thought of as a placeholder for the result of an asynchronous operation, which will be completed at some point in the future and provide access to its results.
2) The JDK is provisioned with the interface java.util.concurrent.Future, but the implementation provided is only allowed to manually check that the corresponding operation has been completed or blocked until it is complete. This is very cumbersome, so Netty provides its own implementation--channelfuture for use when performing asynchronous operations.
3) Channelfuture offers several additional methods that enable us to register one or more Channelfuturelistener instances. The listener's callback method, Operationcomplete (), will be called when the corresponding operation completes. The listener can then determine whether the operation was completed successfully or was in error. If it is the latter, we can retrieve the resulting throwable. In short, the notification mechanism provided by Channelfuturelistener eliminates the need to manually check that the corresponding operation is complete.

4) Each Netty outbound I/O operation will return one ChannelFuture , that is, they will not block. As we mentioned earlier, Netty is completely asynchronous and event-driven.

5.4 Events and Channelhandler

Netty uses different events to inform us of the state change or the state of the operation. This allows us to trigger the appropriate action based on the events that have occurred. These actions may be:

    • Record log;
    • Data conversion;
    • Flow control;
    • Application logic.

Netty is a network programming framework, so events are categorized according to their relevance to inbound or outbound traffic. Events that may be triggered by inbound data or related state changes include:

    • The connection has been activated or the connection is inactivated;
    • Data read;
    • User events;
    • The Error event.

The outbound event is the result of an action that will be triggered in the future, including:

    • Open or close the connection to the remote node;
    • Writes data to or flushes to a socket.

Each event can be distributed to ChannelHandler a method implemented by a user in the class. This is a good example of converting an event-driven paradigm directly into an application artifact block. The diagram shows how an event is handled by one of these ChannelHandler chains.

Netty provides a number of predefined implementations that can be out-of-the-box ChannelHandler , including for various protocols such as HTTP and SSL/TLS ChannelHandler . Internally, you ChannelHandler also use events and Future make them the same abstract consumer that your application will use.

Chapter One: Netty Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.