Sobes.tech
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:

  1. Adding dependencies to pom.xml (Maven) or build.gradle (Gradle).
  2. Configuring producer and consumer properties, such as broker addresses, serializers/deserializers for keys and values.
  3. Creating instances of KafkaProducer and KafkaConsumer.
  4. Sending messages using producer.send() and receiving messages through consumer.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.