繁体   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