Is there away I can send and receive Date type with Apache Avro. I have not been able to find anything on this. Only things I found said that use int and logicalType of Date in schema. But that results in another int on the receiver side. I still have to convert it to date.
I am trying to send date from a Apache Kafka producer and receive in the Kafka consumer.
If there is not other way then do I have to convert date to int always and then back at the consumer. There is this article which shows how to do it:
Get the number of days, weeks, and months, since Epoch in Java
Serializer code:-
@Override
public byte[] serialize(String topic, T data) {
try {
byte[] result = null;
if (data != null) {
logger.debug("data='{}'" + data);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BinaryEncoder binaryEncoder =
EncoderFactory.get().binaryEncoder(byteArrayOutputStream, null);
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(data.getSchema());
datumWriter.write(data, binaryEncoder);
binaryEncoder.flush();
byteArrayOutputStream.close();
result = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
logger.debug("serialized data='{}'" + DatatypeConverter.printHexBinary(result));
}
return result;
} catch (IOException ex) {
throw new SerializationException(
"Can't serialize data='" + data + "' for topic='" + topic + "'", ex);
}
}
desirializer code:-
@Override
public T deserialize(String topic, byte[] data) {
try {
T result = null;
if (data != null) {
logger.debug("data='{}'" + DatatypeConverter.printHexBinary(data));
DatumReader<GenericRecord> datumReader =
new SpecificDatumReader<>(targetType.newInstance().getSchema());
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
result = (T) datumReader.read(null, decoder);
logger.debug("deserialized data='{}'" + result);
}
return result;
} catch (Exception ex) {
throw new SerializationException(
"Can't deserialize data '" + Arrays.toString(data) + "' from topic '" + topic + "'", ex);
}
}
Schema file:-
{"namespace": "com.test",
"type": "record",
"name": "Measures",
"fields": [
{"name": "transactionDate", "type": ["int", "null"], "logicalType" : "date" }
]
}
and these two are just defined as serializer and deserializer classes in producer and consumer configuration.