Start KafKa
Download the decompressed version of KafKa and decompress it locally.
Write zk startup script
./zookeeper-server-start …/…/config/zookeeper.properties
Write kafka startup script
./kafka-server-start …/…/config/server.properties
Start zk
Start kafka
Import dependencies
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.10.1.1</version>
</dependency>
</dependencies>
Producer program
public class Product {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("bootstrap.servers", "127.0.0.1:9092");
properties.put("key.serializer", StringSerializer.class);
properties.put("value.serializer", StringSerializer.class);
KafkaProducer producer = null;
try {
producer = new KafkaProducer(properties);
ProducerRecord record = new ProducerRecord("topic1","info", "hello");
producer.send(record);
} finally {
producer.close();
}
}
}
Consumer program
public class Consumer {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("bootstrap.servers", "127.0.0.1:9092");
properties.put("key.deserializer", StringDeserializer.class);
properties.put("value.deserializer", StringDeserializer.class);
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test1");
KafkaConsumer consumer = new KafkaConsumer(properties);
consumer.subscribe(Collections.singleton("topic1"));
while (true) {
ConsumerRecords poll = consumer.poll(100);
poll.forEach(it -> System.out.println(it));
}
}
}
result
The consumer successfully received the message sent by the producer.