如何识别哪些消息成功发布到kafka主题,哪些消息失败

时间:2019-08-12 16:13:48

标签: java apache-kafka kafka-producer-api

将消息列表发布到apache kafka。谁能使用kafka api提供示例代码,以显示如何识别哪些消息已成功发布到主题,哪些消息因响应而失败? (请注意,我是在一个请求中批量发送邮件列表的。)

1 个答案:

答案 0 :(得分:2)

KafkaProducer.send()方法采用一个ProducerRecord(消息)。

有两种方法可以检查集群是否成功接收到此消息:

  • 使用回调:send()可以将Callback作为第二个参数

    ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
    producer.send(record, new Callback() {
        @Override
        public void onCompletion(RecordMetadata metadata, Exception exception) {
            // If Exception is null, the record was sent successfully
        }
    });
    
  • 使用未来:send()返回一个Future

     ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
     Future<RecordMetadata> future = producer.send(record);
     try {
         RecordMetadata rm = future.get();
         // The record was sent successfully
     } catch (ExecutionException e) {
         // The record failed
     }