ClusterMessageEncoder.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package com.its.common.cluster.codec;
  2. import com.its.common.cluster.vo.ClusterMessage;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.MessageToByteEncoder;
  6. import lombok.extern.slf4j.Slf4j;
  7. import java.io.ByteArrayOutputStream;
  8. import java.io.ObjectOutputStream;
  9. @Slf4j
  10. public class ClusterMessageEncoder extends MessageToByteEncoder<ClusterMessage> {
  11. private final boolean isLogging;
  12. public ClusterMessageEncoder(boolean isLogging) {
  13. this.isLogging = isLogging;
  14. }
  15. @Override
  16. protected void encode(ChannelHandlerContext ctx, ClusterMessage msg, ByteBuf out) throws Exception {
  17. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  18. ObjectOutputStream oos = new ObjectOutputStream(bos);
  19. oos.writeObject(msg);
  20. oos.flush();
  21. byte[] bytes = bos.toByteArray();
  22. if (this.isLogging) {
  23. log.info("ClusterMessageEncoder.encode: SEND {} Bytes.", bytes.length + 4);
  24. }
  25. out.writeInt(bytes.length); // 길이 필드 추가
  26. out.writeBytes(bytes);
  27. oos.close();
  28. bos.close();
  29. }
  30. }