Junior — Middle
How did you integrate Apache Kafka into your Java application?
sobes.tech AI
Answer from AI
To integrate Apache Kafka into a Java application, I used the official Kafka client provided by the kafka-clients library. The main steps included:
- Adding dependencies to
pom.xml(Maven) orbuild.gradle(Gradle). - Configuring producer and consumer properties, such as broker addresses, serializers/deserializers for keys and values.
- Creating instances of
KafkaProducerandKafkaConsumer. - Sending messages using
producer.send()and receiving messages throughconsumer.poll().
Example of sending a message:
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);
producer.send(new ProducerRecord<>("topicName", "key", "value"));
producer.close();
It is also important to handle exceptions properly and manage the lifecycle of the consumer to avoid message loss.