47 lines
1.8 KiB
Java
47 lines
1.8 KiB
Java
package com.mobai.demo;
|
|
|
|
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
|
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
|
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
|
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
|
import org.apache.kafka.common.serialization.StringDeserializer;
|
|
|
|
import java.util.Collections;
|
|
import java.util.Properties;
|
|
|
|
/**
|
|
* demo消费者
|
|
*/
|
|
public class KafkaSimpleConsumer {
|
|
public static void main(String[] args) {
|
|
String bootstrapServers = "127.0.0.1:9092";
|
|
String groupId = "test-group";
|
|
String topic = "testTopic";
|
|
|
|
// 设置消费者属性
|
|
Properties properties = new Properties();
|
|
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
|
|
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
|
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
|
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, groupId);
|
|
properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
|
|
|
|
// 创建消费者
|
|
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
|
|
|
|
// 订阅主题
|
|
consumer.subscribe(Collections.singleton(topic));
|
|
|
|
// 拉取并处理消息
|
|
while(true) {
|
|
ConsumerRecords<String, String> records = consumer.poll(5);
|
|
for (ConsumerRecord<String, String> record : records) {
|
|
System.out.printf("Received message: key = %s, value = %s, offset = %d%n",
|
|
record.key(), record.value(), record.offset());
|
|
}
|
|
}
|
|
|
|
// 注意:实际应用中需要合适的退出机制
|
|
}
|
|
}
|