官术网_书友最值得收藏!

Java Kafka consumer

The following program is a simple Java consumer which consumes data from topic test. Please make sure data is already available in the mentioned topic otherwise no record will be consumed.

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.log4j.Logger;

import java.util.*;

public class DemoConsumer {
private static final Logger log = Logger.getLogger(DemoConsumer.class);

public static void main(String[] args) throws Exception {

String topic = "test1";
List<String> topicList = new ArrayList<>();
topicList.add(topic);
Properties consumerProperties = new Properties();
consumerProperties.put("bootstrap.servers", "localhost:9092");
consumerProperties.put("group.id", "Demo_Group");
consumerProperties.put("key.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
consumerProperties.put("value.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");

consumerProperties.put("enable.auto.commit", "true");
consumerProperties.put("auto.commit.interval.ms", "1000");
consumerProperties.put("session.timeout.ms", "30000");

KafkaConsumer<String, String> demoKafkaConsumer = new KafkaConsumer<String, String>(consumerProperties);

demoKafkaConsumer.subscribe(topicList);
log.info("Subscribed to topic " + topic);
int i = 0;
try {
while (true) {
ConsumerRecords<String, String> records = demoKafkaConsumer.poll(500);
for (ConsumerRecord<String, String> record : records)
log.info("offset = " + record.offset() + "key =" + record.key() + "value =" + record.value());

//TODO : Do processing for data here
demoKafkaConsumer.commitAsync(new OffsetCommitCallback() {
public void onComplete(Map<TopicPartition, OffsetAndMetadata> map, Exception e) {

}
});

}
} catch (Exception ex) {
//TODO : Log Exception Here
} finally {
try {
demoKafkaConsumer.commitSync();

} finally {
demoKafkaConsumer.close();
}
}
}
}
主站蜘蛛池模板: 安多县| 盐边县| 称多县| 宜兰县| 榆社县| 通榆县| 枞阳县| 辽中县| 米泉市| 兴山县| 报价| 南溪县| 舞阳县| 西城区| 常宁市| 通河县| 息烽县| 江西省| 南宫市| 来凤县| 晋中市| 岗巴县| 昌平区| 阿荣旗| 古田县| 武冈市| 垣曲县| 万荣县| 博野县| 准格尔旗| 方城县| 柳江县| 织金县| 岳池县| 南澳县| 马山县| 唐河县| 肇州县| 固安县| 仙居县| 辉南县|