Question : How to handle exception if message lost during publishing to kafka
Answered by : clean-cod-qcyjudrg5pk2
public class ProduceToKafka { private ProducerRecord<String, String> message = null; // TracerBulletProducer class has producer properties private KafkaProducer<String, String> myProducer = TracerBulletProducer .createProducer(); public void publishMessage(String string) { ProducerRecord<String, String> message = new ProducerRecord<>( "topicName", string); myProducer.send(message, new MyCallback(message.key(), message.value())); } class MyCallback implements Callback { private final String key; private final String value; public MyCallback(String key, String value) { this.key = key; this.value = value; } @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception == null) { log.info("--------> All good !!"); } else { log.info("--------> not so good !!"); log.info(metadata.toString()); log.info("" + metadata.serializedValueSize()); log.info(exception.getMessage()); } } }
}
Source : https://stackoverflow.com/questions/40183133/how-to-handle-kafka-publishing-failure-in-robust-way | Last Update : Thu, 22 Apr 21