In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to implement Netty codec based on Protostuff". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to implement Netty codec based on Protostuff.
In the process of designing the codec of netty, there are many components to choose from, and here I am familiar with Protostuff, so I use this component. Because the data is transmitted over the network, the sender needs to convert the class object into binary, and the receiver needs to convert the binary into class object after receiving the data.
Public class SerializeUtil {
Private static class SerializeData {
Private Object target
}
@ SuppressWarnings ("unchecked")
Public static byte [] serialize (Object object) {
SerializeData serializeData = new SerializeData ()
SerializeData.target = object
Class serializeDataClass = (Class) serializeData.getClass ()
LinkedBuffer linkedBuffer = LinkedBuffer.allocate (1024 * 4)
Try {
Schema schema = RuntimeSchema.getSchema (serializeDataClass)
Return ProtostuffIOUtil.toByteArray (serializeData, schema, linkedBuffer)
} catch (Exception e) {
Throw new IllegalStateException (e.getMessage (), e)
} finally {
LinkedBuffer.clear ()
}
}
@ SuppressWarnings ("unchecked")
Public static T deserialize (byte [] data, Class clazz) {
Try {
Schema schema = RuntimeSchema.getSchema (SerializeData.class)
SerializeData serializeData = schema.newMessage ()
ProtostuffIOUtil.mergeFrom (data, serializeData, schema)
Return (T) serializeData.target
} catch (Exception e) {
Throw new IllegalStateException (e.getMessage (), e)
}
}
}
However, the above is only a common operation Util, how to make the data can be transferred on the netty?
In netty, if you want to send data out, you need to convert the data into binary and then send it out over the network. He provides the operation class of MessageToByteEncoder, which users need to inherit, and then implement the encode method. Let's take a look at how we can integrate the SerializeUtil operation class we wrote:
Public class NettyMessageEncoder extends MessageToByteEncoder {
@ Override
Protected void encode (ChannelHandlerContext ctx, NettyMessage msg, ByteBuf out) throws Exception {
Out.writeBytes (SerializeUtil.serialize (msg))
}
}
As shown in the code above, we have a coding class based on the implementation of the Protostuff component. The encoded data is added to the ByteBuf buffer and sent out.
So how to implement the decoder?
Public class NettyMessageDecoder extends LengthFieldBasedFrameDecoder {
Public NettyMessageDecoder (int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
Super (maxFrameLength, lengthFieldOffset, lengthFieldLength)
}
@ Override
Public Object decode (ChannelHandlerContext ctx, ByteBuf in) throws Exception {
Try {
Byte [] dstBytes = new byte [in.readableBytes ()]
/ / in.getBytes (in.readerIndex (), dstBytes)
/ / keep in mind that readBytes must be used here, not getBytes, otherwise readIndex can not be moved backwards, resulting in netty did not read anything but decoded a message. Error
In.readBytes (dstBytes,0,in.readableBytes ())
NettyMessage nettyMessage = SerializeUtil.deserialize (dstBytes, NettyMessage.class)
Return nettyMessage
} catch (Exception e) {
System.out.println ("exception when decoding:" + e)
Return null
}
}
}
As shown in the code above. In general, we need to inherit the ByteToMessageDecoder operation class in netty to achieve, but considering that it is troublesome for users to deal with the problem of unpacking sticky packages themselves, so we inherit from the LengthFieldBasedFrameDecoder prepared for us in netty, because this decoder has the function of dealing with unpacking sticky packages, and it inherits from the ByteToMessageDecoder class, so we do not need to deal with the logic of unpacking sticky packages.
It should be noted that in the process of decoding, we first need to read data from the buffer to the byte array, and then we need to move the readerIndex tag back, if it is not moved after reading, it will report an error of netty did not read anything but decoded a message, and this error will not be thrown out when you run, very hidden, if not carefully debug the client, you will not be able to find the existence of this error.
So as you can see from the above code, ByteBuf.getBytes simply reads the cache data and does not move the readerIndex back. However, ByteBuf.readBytes moves the readerIndex back. This point must be taken seriously.
Finally, we put these two implementation classes in the handler execution container.
Channel.pipeline (). AddLast ("nettyMessageDecoder", new NettyMessageDecoder (1024 * 1024, 4, 4))
Channel.pipeline (). AddLast ("nettyMessageEncoder", new NettyMessageEncoder ())
Channel.pipeline (). AddLast ("readTimeoutHandler", new ReadTimeoutHandler (50))
Channel.pipeline (). AddLast ("loginAuthResponseHandler", new LoginAuthResponseHandler ())
Channel.pipeline (). AddLast ("heartBeatHandler", new HeartBeatResponseHandler ())
Finally, start the service, and we can see that our codec is running normally:
Login is ok: Netty Message [header=Header [crcCode=-1410399999,length=0,sessionId=0,type=4,priority=0,attachment= {}]]
Client send heart beat message to server:-> Netty Message [header=Header [crcCode=-1410399999,length=0,sessionId=1344,type=5,priority=0,attachment= {}]]
Client receive server heartbeat message:-- > Netty Message [header=Header [crcCode=-1410]
At this point, I believe you have a deeper understanding of "how to implement Netty codec based on Protostuff". 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: 0
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.