Integrating Kafka into a Spring Boot application for real-time notifications involves adding Spring Kafka, configuring broker connection properties, and implementing producer and consumer components that publish and react to events on Kafka topics.
Key Points: • Add the spring-kafka dependency and configure bootstrap servers plus producer/consumer serialization settings in application.properties. • A KafkaTemplate is used to publish messages, such as a new notification event, to a topic. • @KafkaListener-annotated methods consume messages from a topic and trigger downstream logic, like pushing a notification to a user. • @EnableKafka activates the annotation-driven Kafka listener infrastructure. • Consumer group IDs control how messages are distributed across multiple instances of the same service for horizontal scaling.
Example: When a user receives a new message, the service publishes a NotificationEvent to a "notifications" topic via KafkaTemplate; a separate notification-delivery service's @KafkaListener consumes that event and pushes it to the user's device in near real time.
Code Example:
@Service
public class NotificationProducer {
private final KafkaTemplate<String, NotificationEvent> kafkaTemplate;
public void publish(NotificationEvent event) {
kafkaTemplate.send("notifications", event);
}
}
@KafkaListener(topics = "notifications", groupId = "notification-service")
public void consume(NotificationEvent event) {
pushService.deliver(event);
}Interview Tip: A concise interview answer is:
"I'd add spring-kafka, configure the broker address and serialization settings, then use a KafkaTemplate to publish notification events to a topic and a @KafkaListener method to consume and deliver them. Consumer groups let me scale the notification service horizontally while Kafka handles the durable, real-time delivery of events."