Describe the integration process of a messaging service like Kafka with a Spring Boot application.

Integrating Kafka with a Spring Boot application involves adding the Spring Kafka dependency, configuring producer and consumer properties, and building components that send and receive messages using Spring Kafka's annotations.

Key Points: • The spring-kafka dependency is added to the build file, pulling in the Kafka client and Spring's integration support. • Producer and consumer properties, such as the broker address, serializers, and consumer group ID, are set in application.properties or application.yml. • A KafkaTemplate bean is used to publish messages to a topic from anywhere in the application, typically wrapped in a small producer service. • A method annotated with @KafkaListener subscribes to a topic and is invoked automatically whenever a new message arrives. • @EnableKafka on a configuration class activates the annotation-driven Kafka listener infrastructure so @KafkaListener methods are picked up.

Example: A Spring Boot order service can publish an OrderPlaced message to a topic via KafkaTemplate.send(), and a separate Spring Boot shipping service, configured with its own consumer group, picks it up through a @KafkaListener method to start the shipping process.

Code Example:

spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      group-id: shipping-service
      auto-offset-reset: earliest
@EnableKafka
@Configuration
public class KafkaConfig {
}

@Component
public class OrderEventListener {
    @KafkaListener(topics = "orders")
    public void onOrder(OrderEvent event) {
        shippingService.schedule(event);
    }
}

Interview Tip: A concise interview answer is:

"I'd add the spring-kafka dependency, configure the broker address and consumer group in application.yml, then use KafkaTemplate to publish messages and a @KafkaListener method, enabled by @EnableKafka, to consume them. That gets a Spring Boot service producing and consuming Kafka messages with very little boilerplate."