使用Kryo替换spring amqp的Java序列化

spring amqp的原生并没有对Kryo加以支持,Kryo的优点就不多说了。

git地址:https://github.com/addozhang/spring-kryo-messaeg-converter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class KryoMessageConverter extends AbstractMessageConverter {
  public static final String CONTENT_TYPE = "application/x-kryo";
  public static final String DEFAULT_CHARSET = "UTF-8";
  private String defaultCharset = DEFAULT_CHARSET;
  private KryoFactory kryoFactory = new DefaultKryoFactory();

  /**
   * Crate a message from the payload object and message properties provided. The message id will be added to the
   * properties if necessary later.
   *
   * @param object            the payload
   * @param messageProperties the message properties (headers)
   * @return a message
   */
  @Override
  protected Message createMessage(Object object, MessageProperties messageProperties) {
      byte[] bytes = null;
      Kryo kryo = kryoFactory.create();
      Output output = new ByteBufferOutput(4096, 1024 * 1024);
      try {
          kryo.writeClassAndObject(output, object);
          bytes = output.toBytes();
      } finally {
          output.close();
      }
      messageProperties.setContentType(CONTENT_TYPE);
      if (messageProperties.getContentEncoding() == null) {
          messageProperties.setContentEncoding(defaultCharset);
      }
      return new Message(bytes, messageProperties);
  }

  @Override
  public Object fromMessage(Message message) throws MessageConversionException {
      Object content = null;
      MessageProperties properties = message.getMessageProperties();
      if (properties != null) {
          if (properties.getContentType() != null && properties.getContentType().contains("x-kryo")) {
              Kryo kryo = kryoFactory.create();
              content = kryo.readClassAndObject(new ByteBufferInput(message.getBody()));
          } else {
              throw new MessageConversionException("Converter not applicable to this message");
          }
      }
      return content;
  }

  private class DefaultKryoFactory implements KryoFactory {

      @Override
      public Kryo create() {
          Kryo kryo = new Kryo();
          return kryo;
      }
  }
}

Comments

comments powered by Disqus