生产者:

package com.db.hadoop.kafka;



import java.util.Properties;
import java.util.Scanner;


import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;


public class ProducerDemo {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "master:9092,slave01:9092,slave02:9092,slave03:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer<>(props);
boolean flag = true;
Scanner input = new Scanner(System.in);
do{
System.out.println("请输入key和value的格式");
producer.send(new ProducerRecord<String, String>("test", input.nextLine(), input.nextLine()));
}while(flag);
producer.close();
}

}


消费者:


package com.db.hadoop.kafka;


import java.util.Arrays;
import java.util.Properties;


import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;




public class ConsumerDemo {
public static void main(String []args){
Properties props = new Properties();
props.put("bootstrap.servers", "master:9092,slave01:9092,slave02:9092,slave03:9092");
props.put("group.id", "test");
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("test"));
boolean flag = true;
while (flag) {
   ConsumerRecords<String, String> records = consumer.poll(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();
}
}

Logo

Kafka开源项目指南提供详尽教程,助开发者掌握其架构、配置和使用,实现高效数据流管理和实时处理。它高性能、可扩展,适合日志收集和实时数据处理,通过持久化保障数据安全,是企业大数据生态系统的核心。

更多推荐