ProtobufKryoSerializer.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package com.sdyc.ndmp.protobuf.serializer;
  2. import com.esotericsoftware.kryo.*;
  3. import com.esotericsoftware.kryo.io.Input;
  4. import com.esotericsoftware.kryo.io.Output;
  5. import com.google.protobuf.GeneratedMessage;
  6. /**
  7. * <pre>
  8. *
  9. * Created by IntelliJ IDEA.
  10. * User: zhenqin
  11. * Date: 14/12/10
  12. * Time: 09:55
  13. * To change this template use File | Settings | File Templates.
  14. *
  15. * </pre>
  16. *
  17. * @author zhenqin
  18. */
  19. public class ProtobufKryoSerializer extends com.esotericsoftware.kryo.Serializer<GeneratedMessage> {
  20. protected final ProtobufSerializer protobufSerializer;
  21. public ProtobufKryoSerializer() {
  22. protobufSerializer = new ProtobufSerializer();
  23. }
  24. @Override
  25. public void write(Kryo kryo, Output output, GeneratedMessage object) {
  26. byte[] bytes = protobufSerializer.serialize(object);
  27. output.writeInt(bytes.length, false);
  28. output.write(bytes);
  29. }
  30. @Override
  31. public GeneratedMessage read(Kryo kryo, Input input, Class type) {
  32. int i = input.readInt(false);
  33. byte[] bytes = new byte[i];
  34. input.read(bytes);
  35. return protobufSerializer.deserialize(bytes);
  36. }
  37. }