Get the App
SLTechnology News&Howtos  ›  Servers  › 

The solution to the problem of sticking package in Netty

Shulou Source: shulou.com Published: 2022-06-01 15:05:17 09月25日 Update

This article mainly explains "the solution to the Netty sticky package problem". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn the solution to the Netty sticky bag problem.

We know that there are boss threads and worker threads in netty, which is usually an one-to-many relationship, which can be understood as that after receiving a customer's request, boss is assigned to one of the worker to deal with it. If there are too many customers, one worker may serve multiple customers. This is the background.

According to my understanding, the key to solving the sticky packet problem lies in two points: 1, the received data can not be parsed in time, there must be a place to save it; 2, the arbitrary movement of the buffer pointer; as it happens, these two points netty can be very easy. The following is the code, which will hide the specific business part because of the company's confidentiality requirements.

Public class ProtocolAnaDecoder extends ByteToMessageDecoder {

@ Override

Protected void decode (ChannelHandlerContext ctx, ByteBuf in, Listout) throws Exception {Object decoded = null

While (true) {

Decoded = decode (ctx, in)

If (decoded! = null) {

Out.add (decoded)

} else {

Return

}

}

}

Private Object decode (ChannelHandlerContext ctx, ByteBuf in) {

/ / Mark the current read pointer position

In.markReaderIndex ()

While (in.isReadable ()) {

Byte b = in.readByte ()

/ / in the business processing part, if you get a correct message object, return it directly

}

/ / if no message object is obtained, reset the position of the read pointer (the position of the previous mark). In.resetReaderIndex ()

Return null

}

}

At this point, I believe you have a deeper understanding of the "solution to the Netty sticky package problem". 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!

Tags: Method problem location customer pointer business content object situation message thread part processing learning utility deeper code company key interest Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Technology Redmi MariaDB macOS