带回调函数的异步发送
回调函数在producer受到ack时调用,为异步函数,该方法有两个参数,分别是原数据信息(recordMetaData)和异常信息(Exception)。如果Exception为null,说明消息发送成功,如果Exception 不为null,说明消息发送失败。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/dcff55505e6344a30932a37b6df6e600.png)
参考代码
public class CustomKafkaProviderCallback {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
for (int i = 0; i < 10; i++) {
kafkaProducer.send(new ProducerRecord<>("quickstart-events", "record:" + i), new Callback() {
@Override
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
if (e == null) {
System.out.println("主题:" + recordMetadata.topic());
}
}
});
}
kafkaProducer.close();
}
}