Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure the maven of netty

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to configure the maven of netty". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to configure the maven of netty"!

Netty is widely used in various scenarios, such as remote communication of Dubbo services, shuffle process of Hadoop, client and server communication in the field of games, and so on. Netty can easily define a variety of private protocol stacks and is a powerful tool for network programming. Netty encapsulates NIO, while Netty does not encapsulate AIO because Linux's AIO is also implemented with epoll, so the performance is not greatly improved, and the reactor model of Netty is not suitable for encapsulating AIO, so Netty gives up support for AIO. With the rise of the Internet of things, a large number of devices need to be interconnected, and Netty must be a sharp weapon among them.

In the traditional NIO programming model, we need to use the poller selector to poll whether there are read and write events in each channel, and the ByteBuffer api is obscure, the maintenance is very complex, and the business is difficult to decouple. Netty helps us shield the details of NIO and do a lot of performance optimization. Let's take a look at some details in Netty.

Note: the following example netty version number is 4.1.52.FinalMagne maven configuration is as follows:

4.0.0 org.netty netty-demo 0.0.1-SNAPSHOT jar netty-demo http://maven.apache.org UTF-8 io.netty netty-all 4.1.52.Final

First, the startup of client and server

1. Server end

The group method in ServerBootstrap has two input parameters, NioEventLoopGroup, and two thread pools, which represent the thread that accepts the request and the thread that processes the request. This is the embodiment of the reactor model. Each client connects to the server, there is a channel corresponding to it. The childHandler method binds a bunch of processors to the channel, which binds three inbound processors. Ctx.fireChannelRead (msg) indicates that the lower-level processor is notified of processing, and if this method is not called, the read event will be terminated and propagated to the downstream processor.

Public class NettyDemoServer {public static void main (String [] args) {ServerBootstrap serverBootstrap = new ServerBootstrap () ServerBootstrap.group (new NioEventLoopGroup () New NioEventLoopGroup () .channel (NioServerSocketChannel.class) .childHandler (new ChannelInitializer () {@ Override protected void initChannel (NioSocketChannel ch) throws Exception {ch.pipeline () .addLast ( New StringDecoder () .addLast (new SimpleChannelInboundHandler () {@ Override protected void channelRead0 (ChannelHandlerContext ctx) Object msg) throws Exception {System.out.println ("Handler1:" + msg) Ctx.fireChannelRead (msg) ) .addLast (new SimpleChannelInboundHandler () {@ Override protected void channelRead0 (ChannelHandlerContext ctx) Object msg) throws Exception {System.out.println ("Handler2:" + msg) Ctx.fireChannelRead (msg);}}) }}) .bind (8080) .addListener (o-> {if (o.isSuccess ()) {System.out.println ("start successfully") });}}

2. Client

The client encodes as a string and writes a piece of data to the server every three seconds.

Public class NettyDemoClient {public static void main (String [] args) {Bootstrap bootstrap = new Bootstrap (); NioEventLoopGroup group = new NioEventLoopGroup () Bootstrap.group (group) .channel (NioSocketChannel.class) .handler (new ChannelInitializer () {@ Override protected void initChannel (Channel ch) {ch.pipeline () .handler (new StringEncoder ());}}) Channel channel = bootstrap.connect ("localhost", 8080). Channel (); while (true) {channel.writeAndFlush (new Date (). ToLocaleString () + ": test netty"); try {Thread.sleep (3000) } catch (InterruptedException e) {e.printStackTrace ();}}

The running effect is as follows:

Successfully launched Handler1:2020-9-11 17:23:19: test nettyHandler2:2020-9-11 17:23:19: test nettyHandler1:2020-9-11 17:23:23: test nettyHandler2:2020-9-11 17:23:23: test nettyHandler1:2020-9-11 17:23:26: test nettyHandler2:2020-9-11 17:23:26: test netty

Netty shields all the details of IO processing, and only needs to define that there is no inbound and outbound processors to deal with the corresponding business, thus realizing the decoupling of business and communication.

Data processing channel pipeline and channel processor channelHandler

1 、 channelHandler

Inheriting from ChannelHandler, there are two interfaces, ChannelInboundHandler and ChannelOutBoundHandler, which represent inbound and outbound interfaces respectively. For example, for inbound processors, the channelRead (ChannelHandlerContext ctx, Object msg) method will be triggered when messages come in, and for outbound processors, write (ChannelHandlerContext ctx, Object msg, ChannelPromise promise) will be triggered when data is written out. ChannelInboundHandlerAdapter and ChanneloutBoundHandlerAdapter are common implementations of the two types of interfaces. There are some very simple implementations that simply pass read and write events in pipeline.

2. Event propagation sequence of pipeline

For inbound processors, the execution order is consistent with the order in which addLast is added, which has been verified in the previous print example, and for outbound processors, the execution order is the opposite of the order in which addLast is added. Let's verify this on the client side and add two outbound processors on the client side.

Public class NettyDemoClient {public static void main (String [] args) {Bootstrap bootstrap = new Bootstrap (); NioEventLoopGroup group = new NioEventLoopGroup () Bootstrap.group (group) .channel (NioSocketChannel.class) .handler (new ChannelInitializer () {@ Override protected void initChannel (Channel ch) {ch.pipeline () .addLast (new StringEncoder ()) .addLast (new OutBoundHandlerFirst ()) .addLast (new OutBoundHandlerSecond () }}); Channel channel = bootstrap.connect ("localhost", 8080). Channel (); while (true) {channel.writeAndFlush (new Date (). ToLocaleString () + ": test netty") Try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace () } public static class OutBoundHandlerFirst extends ChannelOutboundHandlerAdapter {@ Override public void write (ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {System.out.println ("OutBoundHandlerFirst"); super.write (ctx, msg, promise) } public static class OutBoundHandlerSecond extends ChannelOutboundHandlerAdapter {@ Override public void write (ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {System.out.println ("OutBoundHandlerSecond"); super.write (ctx, msg, promise);}

Print the log as follows:

OutBoundHandlerSecondOutBoundHandlerFirstOutBoundHandlerSecondOutBoundHandlerFirstOutBoundHandlerSecondOutBoundHandlerFirstOutBoundHandlerSecondOutBoundHandlerFirstOutBoundHandlerSecondOutBoundHandlerFirst

Here we verify that the outbound processor is executed in reverse order to the order in which addLast is added.

Pipeline actually maintains a two-way linked list. Why does this happen? We found the answer in AbstractChannelHandlerContext. The findContextInbound method takes the next node, and the findContextOutbound takes the previous node.

Private AbstractChannelHandlerContext findContextInbound () {AbstractChannelHandlerContext ctx = this; do {ctx = ctx.next;} while (! ctx.inbound); return ctx;} private AbstractChannelHandlerContext findContextOutbound () {AbstractChannelHandlerContext ctx = this; do {ctx = ctx.prev;} while (! ctx.outbound); return ctx;}

III. Processor life cycle

When a connection is established, handlerAdded- > channelRegistered- > channelActive- > channelRead- > channelReadComplete

When the connection is closed, channelInactive- > channelUnregistered- > handlerRemoved

Description: each time channelRead and channelReadComplete finish reading the complete packet, these two methods are called

Fourth, unpacking and sticking to solve the problem

TCP protocol is a streaming protocol, so when transmitting data, a complete packet will not be transmitted according to our business. Multiple packets may be sent together. At this time, the receiver needs to unpack the packet, or it can split a complete packet into multiple packets for transmission. At this time, the receiver needs to merge multiple packets into a complete packet to parse. So what are the plans for netty?

1. Fixed-length unpacking device FixedLengthFrameDecoder

Each packet has a fixed length, for example, each packet is 50, which is suitable for simple scenarios.

2. Line unpacker LineBasedFrameDecoder

Unpack with newline characters

3. Delimiter unpacker DelimiterBasedFrameDecoder

This is similar to the separator, except that you can customize special symbols to unpack, such as # @, which must be used to make sure that there are no such special symbols in the official message.

4. Length domain unpacker LengthFieldBasedFrameDecoder

This is the most general-purpose unpacking device, based on which almost all binary custom protocols can be unpacked, as long as a length field is defined in the protocol header, for example, 4 bytes are used to store the length of the message body

At this point, I believe you have a deeper understanding of "how to configure the maven of netty". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 274

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report