簡體   English   中英

是否可以分別使用來自 kafka 主題的每條消息?

[英]Is it posible to consume each message from a kafka topic separately?

好的,目標是:我有一個應該發送郵件的服務,如果失敗,我的 Kafka 生產者會將此郵件發送到 Kafka 主題。 第二個程序每兩分鍾查看一次主題,並且應該只使用一條消息(最舊的一條)並重試發送它,如果失敗,程序應該將此消息帶回主題。

我已經有一個消費者,但問題是,它消費了我到現在為止沒有消費的所有消息。 但我希望他只吃最老的,他以前沒有吃過。

這是我的實際消費者:

“customMessage”是我為測試創建的 class,它只是一個 object,具有不同的屬性,如日期、消息和其他內容。 為了測試代碼有點修改,所以這個消費者正在運行。 它也只顯示消息而不是處理它,所以只有“ System.out.println(message.displayMessage()); “。

公共 class ConsumerOne {

public static void main(String[] args) {

    Properties properties = new Properties();
    properties.put("bootstrap.servers", "localhost:9092");
    properties.put("group.id", "happyConsumer");
    properties.put("auto.offset.reset", "earliest");
    properties.put("enable.auto.commit", "false");
    properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

    KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

    consumer.subscribe(Arrays.asList("mymailtopic"));

    while (true) {
        ObjectMapper om = new ObjectMapper();
        ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
        for (ConsumerRecord<String, String> record : records) {
            customMessage message=null;
            try {
                 message = om.readValue(record.value(), customMessage.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            System.out.println(message.displayMessage());
        }
    }


}

}

使用實際代碼,該服務也可以工作,但我至少可以嘗試它是否也可以像我在第一段中提到的那樣工作。 所以,我的問題是:

  1. 是否甚至可以只使用來自該主題的一條消息?
  2. 如果是,我該怎么做?

我在整個服務中使用 Java 和 quarkus(我認為是最新版本的 Kafka)。

您可以使用max.poll.records屬性逐條消息消費,在配置中將此屬性設置為1

在一次 poll() 調用中返回的最大記錄數。

properties.put("max.poll.records", 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM