使用Java语言实现kafka简单的生产消费模型
时间: 2023-03-03 13:44:11 浏览: 126
好的,下面是使用Java语言实现kafka简单的生产消费模型的步骤:
1. 首先,需要引入kafka的Java客户端依赖,可以在Maven或Gradle中添加以下依赖:
```
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>{kafka版本号}</version>
</dependency>
```
2. 编写生产者代码,创建KafkaProducer对象,设置producer配置,然后通过调用send()方法向指定的Topic发送消息,示例代码如下:
```
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
ProducerRecord<String, String> record = new ProducerRecord<>("test_topic", "key", "value");
producer.send(record);
producer.close();
```
3. 编写消费者代码,创建KafkaConsumer对象,设置consumer配置和消费者订阅的Topic,然后通过轮询poll()方法获取Topic中的消息,示例代码如下:
```
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("group.id", "test_group");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("test_topic"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
}
```
以上就是使用Java语言实现kafka简单的生产消费模型的步骤,你可以根据自己的需求进行修改和扩展。
阅读全文