CompressProtobufKryoSerializer.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.sdyc.ndmp.protobuf.serializer;
  2. import com.esotericsoftware.kryo.Kryo;
  3. import com.esotericsoftware.kryo.io.Input;
  4. import com.esotericsoftware.kryo.io.Output;
  5. import com.google.protobuf.GeneratedMessage;
  6. import java.lang.reflect.InvocationTargetException;
  7. import java.lang.reflect.Method;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. /**
  11. * <pre>
  12. *
  13. * Created by IntelliJ IDEA.
  14. * User: zhenqin
  15. * Date: 14/12/10
  16. * Time: 09:55
  17. * To change this template use File | Settings | File Templates.
  18. *
  19. * </pre>
  20. *
  21. * @author zhenqin
  22. */
  23. public class CompressProtobufKryoSerializer extends com.esotericsoftware.kryo.Serializer<GeneratedMessage> {
  24. /**
  25. * 内部缓存
  26. */
  27. protected final static Map<Class<?>, Method> CLASS_METHOD_MAP = new HashMap<Class<?>, Method>(3);
  28. public CompressProtobufKryoSerializer() {
  29. }
  30. @Override
  31. public void write(Kryo kryo, Output output, GeneratedMessage object) {
  32. byte[] bytes = object.toByteArray();
  33. output.writeInt(bytes.length, false);
  34. output.write(bytes);
  35. }
  36. @Override
  37. public GeneratedMessage read(Kryo kryo, Input input, Class type) {
  38. int i = input.readInt(false);
  39. byte[] bytes = new byte[i];
  40. input.read(bytes);
  41. try {
  42. return reflact(type, bytes);
  43. } catch (Exception e) {
  44. throw new IllegalStateException(e);
  45. }
  46. }
  47. protected static GeneratedMessage reflact(Class aClass, byte[] args)
  48. throws ClassNotFoundException, NoSuchMethodException,
  49. InvocationTargetException, IllegalAccessException {
  50. Method method = CLASS_METHOD_MAP.get(aClass);
  51. if (method == null) {
  52. method = aClass.getMethod("parseFrom", byte[].class);
  53. CLASS_METHOD_MAP.put(aClass, method);
  54. }
  55. return (GeneratedMessage) method.invoke(null, args);
  56. }
  57. }