public class ProducerDemo {
public static String topic = "demo";
public static void main(String[] args) throws Exception {
final Properties properties = new Properties();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "master-node:9092,node-1:9092,node-2:9092");
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
KafkaProducer kafkaProducer = new KafkaProducer<>(properties);
try {
while (true) {
String msg = "Hello, " + new Random().nextInt(100);
ProducerRecord record = new ProducerRecord<>(topic, msg);
kafkaProducer.send(record);
System.out.println("消息发送成功: " + msg);
Thread.sleep(500);
}
} finally {
kafkaProducer.close();
}
}
}
public class ConsumerDemo {
public static void main(String[] args) {
final Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "master-node:9092,node-1:9092,node-2:9092");
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "demo");
KafkaConsumer kafkaConsumer = new KafkaConsumer<>(properties);
kafkaConsumer.subscribe(Collections.singletonList(ProducerDemo.topic));
while (true) {
ConsumerRecords records = kafkaConsumer.poll(100);
for (ConsumerRecord record : records
) {
System.out.println(String.format("topic:%s,offset:%d,消息:%s", record.topic(), record.offset(), record.value()));
}
}
}
}