I know in KafkaJS we can consume message with the following code
const run = async () => {
await kafkaClient.consumer.subscribe({ topic: 'mytopic', fromBeginning: true })
await kafkaClient.consumer.run({
eachBatchAutoResolve: false,
eachBatch: async ({ batch, resolveOffset, heartbeat, isRunning, isStale }) => {
for (let message of batch.messages) {
if (!isRunning() || isStale()) break
processMessage(message)
resolveOffset(message.offset)
}
},
})
}
And the message format is like this
{
magicByte: 2,
attributes: 0,
timestamp: '540669',
offset: '601953',
key: <Buffer 39 63 37 23>,
value: <Buffer 7b 65 32 65 37 38 ... 555 more bytes>,
headers: {
'myheader': <Buffer 61 6f>,
},
‧‧‧‧‧‧
}
But now I'm using KafkaListener in spring boot as consumer.
@org.springframework.kafka.annotation.KafkaListener(
topics = "mykafkatopic",
groupId = "groupId"
)
void listener(WhatTypeShouldThisBe data){
}
}
In JS, the type of the message is object
, so I'm confused about what type of object should be used in the java listener function to receive the message?
And the messages produced by KafkaJS are serialized, how to deal with the serialization in java consumer?
Update1: Should I define a class like this
public class messageFormat{
int magicBytes;
‧‧‧
byte[] key;
selfDefinedHeaderClass header;
}
And then modify the ConsumerFactory
function to this
public ConsumerFactory<String, messageFormat> consumerFactory() {
// ...
return new DefaultKafkaConsumerFactory<>(
props,
new StringDeserializer(),
new JsonDeserializer<>(messageFormat.class));
}