- Building Data Streaming Applications with Apache Kafka
- Manish Kumar Chanchal Singh
- 179字
- 2022-07-12 10:38:17
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();
}
}
}
}
推薦閱讀
- DB2 V9權(quán)威指南
- 軟件界面交互設(shè)計基礎(chǔ)
- Learning ELK Stack
- Getting Started with Python and Raspberry Pi
- Django實戰(zhàn):Python Web典型模塊與項目開發(fā)
- Web App Testing Using Knockout.JS
- SQL Server 入門很輕松(微課超值版)
- AMP:Building Accelerated Mobile Pages
- PowerDesigner 16 從入門到精通
- Arduino電子設(shè)計實戰(zhàn)指南:零基礎(chǔ)篇
- Applied Deep Learning with Python
- TypeScript全棧開發(fā)
- Python數(shù)據(jù)科學(xué)實踐指南
- Java設(shè)計模式深入研究
- Learning TypeScript