com.godmao.mqbroker.handler.TopicSyncMessageEncoderHandler Maven / Gradle / Ivy
package com.godmao.mqbroker.handler;
import com.godmao.mqbroker.message.TopicSyncMessage;
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.HashMap;
import java.util.Map;
/**
* 同步主题消息处理器
*/
@ChannelHandler.Sharable
public class TopicSyncMessageEncoderHandler extends AbstractEncoderHandler {
public static final TopicSyncMessageEncoderHandler INSTANCE = new TopicSyncMessageEncoderHandler();
@Override
public ByteBuf encode(TopicSyncMessage msg) {
final Map topicCount = msg.getTopicCount();
final int topicCount_size = topicCount.size();
// 预估缓冲区大小
int estimatedSize = 14;// cmd(1 byte) + version(8 bytes) + replace(1 bytes) + size(4 bytes)
final Map topicByteCount = new HashMap<>(topicCount_size);
for (Map.Entry entry : topicCount.entrySet()) {
final byte[] topic_bytes = entry.getKey().getBytes(StandardCharsets.UTF_8);
topicByteCount.put(topic_bytes, entry.getValue());
estimatedSize += 4 + topic_bytes.length;
}
final ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(estimatedSize);
byteBuf.writeByte(msg.getCmd()); // 1
byteBuf.writeLong(msg.getVersion()); // 8
byteBuf.writeBoolean(msg.isReplace());// 1
byteBuf.writeInt(topicCount_size); // 4
for (Map.Entry entry : topicByteCount.entrySet()) {
final byte[] topic_bytes = entry.getKey();
byteBuf.writeInt(topic_bytes.length);
byteBuf.writeBytes(topic_bytes);
byteBuf.writeInt(entry.getValue());
}
return byteBuf;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy