简体   繁体   中英

How to implement deserialize method in Kafka Deserializer?

I am making my first Apache Kafka consumer. So this example seems nice. https://www.safaribooksonline.com/library/view/kafka-the-definitive/9781491936153/ch04.html I am having problem with implementing deserialize method. Say that I have address field in Customer. I guess I should make AddressDeserializer but how to know how many bytes that AddressDeserializer will need to read? Address have lets say 3 String fields but sometimes some of them are null. So should I pass to it 3*8 bytes? I guess that is not solution. Also, buffer.get(nameBytes) method seems so unnatural for me because of that in parameter that is the out parameter at the same time, that is bad practice. Is that the right aprroach to retrieve bytes or I am missing something? Thank you in advance.

@Override
  public Customer deserialize(String topic, byte[] data) {

    int id;
    int nameSize;
    String name;

    try {
      if (data == null)
        return null;
      if (data.length < 8)
        throw new SerializationException("Size of data received by IntegerDeserializer is shorter than expected");

      ByteBuffer buffer = ByteBuffer.wrap(data);
      id = buffer.getInt();
      String nameSize = buffer.getInt();

      byte[] nameBytes = new Array[Byte](nameSize);
      buffer.get(nameBytes);
      name = new String(nameBytes, 'UTF-8');

      return new Customer(id, name); 2

    } catch (Exception e) {
      throw new SerializationException("Error when serializing Customer to byte[] " + e);
    }
  }   

Here, Jackson library should be used. Add ObjectMapper as dependency and then:

return objectMapper.readValue(data, Customer.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM