编写java连接kafka生产和消费json文件消息
时间: 2023-07-15 18:15:00 浏览: 223
kafka及Json库
连接Kafka生产和消费JSON格式的消息,可以使用Kafka提供的Java客户端库。以下是一个简单的示例代码:
生产者代码:
```java
import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.json.JSONObject;
public class KafkaProducerExample {
public static void main(String[] args) {
// 设置Kafka的配置属性
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");
// 创建Kafka生产者实例
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
// 构建JSON格式的消息
JSONObject json = new JSONObject();
json.put("name", "张三");
json.put("age", 25);
json.put("address", "北京市朝阳区");
// 发送JSON消息
ProducerRecord<String, String> record = new ProducerRecord<>("test_topic", json.toString());
producer.send(record);
// 关闭Kafka生产者实例
producer.close();
}
}
```
消费者代码:
```java
import java.util.Collections;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.json.JSONObject;
public class KafkaConsumerExample {
public static void main(String[] args) {
// 设置Kafka的配置属性
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");
// 创建Kafka消费者实例
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
// 订阅消息主题
consumer.subscribe(Collections.singletonList("test_topic"));
// 循环消费消息
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
// 解析JSON格式的消息
JSONObject json = new JSONObject(record.value());
String name = json.getString("name");
int age = json.getInt("age");
String address = json.getString("address");
System.out.printf("收到消息:name=%s, age=%d, address=%s\n", name, age, address);
}
}
// 关闭Kafka消费者实例
consumer.close();
}
}
```
请注意,以上示例代码仅用于演示如何在Java中连接Kafka并生产/消费JSON格式的消息。实际应用中可能需要更复杂的代码来处理错误、配置和批量处理等问题。
阅读全文