用java写一个kafka3.5.1的demo
时间: 2024-09-23 07:06:19 浏览: 41
kafka-3.5.1
在Java中编写一个Kafka 3.5.1的基本消费者示例,你可以使用`org.apache.kafka.clients.consumer.Consumer` API。首先确保已经添加了Kafka的依赖到你的项目中。以下是简单的步骤和代码:
```java
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.util.Arrays;
import java.util.Properties;
public class KafkaDemo {
private static final String BOOTSTRAP_SERVERS = "localhost:9092"; // 替换为你服务器的实际地址
private static final String TOPIC = "testTopic"; // 你要消费的主题
public static void main(String[] args) {
Properties props = new Properties();
// 设置属性
props.put("bootstrap.servers", BOOTSTRAP_SERVERS);
props.put("group.id", "testGroup"); // 消费者组ID
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList(TOPIC));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100); // 每隔100毫秒拉取消息
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
}
consumer.close();
}
}
```
这个例子创建了一个消费者,连接到指定的Kafka服务器,并订阅一个主题。它会不断地从该主题拉取消息并打印出来。
阅读全文