簡體   English   中英

Apache Kafka中的消息使用確認

[英]Message consumption acknowledgement in Apache Kafka

我已經實現了一個Java Consumer,它使用來自Kafka主題的消息,然后將這些消息與POST請求一起發送到REST API。

    while (true) {
        ConsumerRecords<String, Object> records = consumer.poll(200);
        for (ConsumerRecord<String, Object> record : records) {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();  
            Object message = record.value();
            JSONObject jsonObj = new JSONObject(message.toString());
            try {
                HttpPost request = new HttpPost(this.getConsumerProperties().getProperty("api.url"));
                StringEntity params = new StringEntity(message.toString());
                request.addHeader("content-type", "application/json");
                request.addHeader("Accept", "application/json");
                request.setEntity(params);

                CloseableHttpResponse response = httpClient.execute(request);
                HttpEntity entity = response.getEntity();
                String responseString = EntityUtils.toString(entity, "UTF-8");
                System.out.println(message.toString());
                System.out.println(responseString);
            } catch(Exception ex) {
              ex.printStackTrace();
            }  finally {
                try {   
                    httpClient.close(); 
                } catch(IOException ex) {
                    ex.printStackTrace();
                } 
            }                  
        } 
    }   

假設消息已被使用,但Java類無法訪問REST API。 郵件永遠不會被傳遞,但會被標記為已消耗。 處理此類案件的最佳方法是什么? 當且僅當REST API的響應成功時,我才能以某種方式確認消息嗎?

在使用者屬性中,將enable.auto.commit設置為false。 這意味着承諾抵消的責任在於消費者。

因此,在上面的示例中,基於response.statusCode,您可以選擇通過調用consumer.commitAsync()來提交偏移量。

暫無
暫無

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

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