KryoSerializer.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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.common.collect.ImmutableMap;
  6. import com.google.protobuf.GeneratedMessage;
  7. import com.sdyc.ndmp.protobuf.dubbo.support.KryoFactory;
  8. import java.io.ByteArrayInputStream;
  9. import java.io.ByteArrayOutputStream;
  10. import java.util.Map;
  11. /**
  12. * <pre>
  13. *
  14. * Created by IntelliJ IDEA.
  15. * User: zhenqin
  16. * Date: 14/12/10
  17. * Time: 09:27
  18. * To change this template use File | Settings | File Templates.
  19. *
  20. * </pre>
  21. *
  22. * @author zhenqin
  23. */
  24. public class KryoSerializer<T> implements Serializer<T> {
  25. protected final Kryo kryo;
  26. protected final Class<T> objectClass;
  27. public KryoSerializer(Class<T> objectClass) {
  28. this(objectClass,
  29. ImmutableMap.<Class<?>, com.esotericsoftware.kryo.Serializer>of(
  30. GeneratedMessage.class, new ProtobufKryoSerializer()));
  31. }
  32. public KryoSerializer(Class<T> objectClass, Map<Class<?>, com.esotericsoftware.kryo.Serializer> classMap) {
  33. kryo = new Kryo();
  34. for (Map.Entry<Class<?>, com.esotericsoftware.kryo.Serializer> entry : classMap.entrySet()) {
  35. kryo.register(entry.getKey(), entry.getValue());
  36. }
  37. this.objectClass = objectClass;
  38. }
  39. protected KryoSerializer(Kryo kryo, Class<T> objectClass) {
  40. this.kryo = kryo;
  41. this.objectClass = objectClass;
  42. }
  43. public static <S> KryoSerializer<S> getKryoSerializer(Class<S> objectClass) {
  44. return new KryoSerializer<S>(KryoFactory.newInstance(), objectClass);
  45. }
  46. public static <S> KryoSerializer<S> getKryoSerializer(KryoFactory.Call call, Class<S> objectClass) {
  47. return new KryoSerializer<S>(KryoFactory.newInstance(call), objectClass);
  48. }
  49. @Override
  50. public byte[] serialize(T o) {
  51. ByteArrayOutputStream out = new ByteArrayOutputStream();
  52. Output output = new Output(out);
  53. kryo.writeObject(output, o);
  54. output.flush();
  55. return out.toByteArray();
  56. }
  57. @Override
  58. public T deserialize(byte[] bytes) {
  59. return deserialize(bytes, this.objectClass);
  60. }
  61. public T deserialize(byte[] bytes, Class<T> clazz) {
  62. ByteArrayInputStream in = new ByteArrayInputStream(bytes);
  63. Input input = new Input(in);
  64. return kryo.readObject(input, clazz);
  65. }
  66. }