有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在kafka关闭时发送消息时没有异常

我有一个场景,卡夫卡正在随机下山。当我向卡夫卡发送消息时,消息关闭了,我想单独处理。但当我在卡夫卡倒下时向其发送消息时,不会出现异常,因此我无法确定卡夫卡是否倒下。是否有任何方法可以捕获异常和丢失的消息

我有一个非常基本的代码

public static void main(String[] args) {
    String topicName = "test-1";

    Properties props = new Properties();
    props.put("bootstrap.servers", "localhost:9092");
    props.put("acks", "all");
    props.put("retries", 0);
    props.put("batch.size", 16384);
    props.put("linger.ms", 1);
    props.put("buffer.memory", 33554432);
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

    Producer<String, String> producer = new KafkaProducer<>(props);

    for (int i = 0; i < 10; i++) {
        producer.send(new ProducerRecord<>(topicName, Integer.toString(i), Integer.toString(i)));
    }
    System.out.println("Message sent successfully");
    producer.close();
}

共 (1) 个答案

  1. # 1 楼答案

    你需要发送一个同步电话才能从卡夫卡那里得到回复

    for (int i = 0; i < 10; i++) {
        ProducerRecord<String, String> record = 
                  new ProducerRecord<>(topicName, Integer.toString(i), Integer.toString(i));
        try {
               producer.send(record).get();
        } catch (Exception e) {
               e.printStackTrace();
               // Handle message that has failed
        }
    }
    

    方法.get()将返回来自卡夫卡的响应。当记录未能推送到卡夫卡时,它将抛出异常。成功发送记录后,将返回RecordMetadata