All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.godmao.mqbroker.handler.MultipleMessageEncoderHandler Maven / Gradle / Ivy

There is a newer version: 0.2.7.RELEASE
Show newest version
package com.godmao.mqbroker.handler;

import com.godmao.mqbroker.message.MultipleMessage;
import com.godmao.netty.handler.AbstractEncoderHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandler;

import java.nio.charset.StandardCharsets;
import java.util.List;

@ChannelHandler.Sharable

public class MultipleMessageEncoderHandler extends AbstractEncoderHandler {
    public static final MultipleMessageEncoderHandler INSTANCE = new MultipleMessageEncoderHandler();

    @Override
    public ByteBuf encode(MultipleMessage.Response msg) {

        final List topics = msg.getTopics();
        final List datas = msg.getDatas();

        // 预估缓冲区大小
        int estimatedSize = 9; // cmd(1 byte) + topics.size(4 bytes) + datas.size(4 bytes)
        final byte[][] _topics_bytes = new byte[topics.size()][];

        for (int i = 0; i < topics.size(); i++) {
            final String topic = topics.get(i);
            final byte[] topic_bytes = topic.getBytes(StandardCharsets.UTF_8);
            _topics_bytes[i] = topic_bytes;
            estimatedSize += 4 + topic_bytes.length;
        }

        for (byte[] data : datas) {
            estimatedSize += 4 + data.length;
        }

        final ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(estimatedSize);
        byteBuf.writeByte(msg.getCmd());// 1
        byteBuf.writeInt(topics.size());// 4
        byteBuf.writeInt(datas.size()); // 4

        for (final byte[] topic_bytes : _topics_bytes) {
            byteBuf.writeInt(topic_bytes.length);
            byteBuf.writeBytes(topic_bytes);
        }

        for (final byte[] data : datas) {
            byteBuf.writeInt(data.length);
            byteBuf.writeBytes(data);
        }

        return byteBuf;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy