Interview question
What is Spring Cloud Stream and how does it abstract message brokers? Spring Cloud Stream क्या है और यह message brokers को कैसे abstract करता है?
Answer
Spring Cloud Stream provides a unified programming model for building message-driven microservices, abstracting underlying broker details (Kafka, RabbitMQ, etc.). Use suppliers, functions, and consumers to decouple from specific implementations.
// Spring Cloud Stream with Kafka/RabbitMQ abstraction
// application.yml
spring:
cloud:
stream:
bindings:
input:
destination: orders
group: order-processor
output:
destination: notifications
kafka: # or rabbit
binder:
brokers: localhost:9092
// Supplier (Producer)
@Configuration
public class OrderProducer {
@Bean
public Supplier<Order> orderSupplier() {
return () -> new Order('ORD-001', 100.0);
}
}
// Function (Processor)
@Configuration
public class OrderProcessor {
@Bean
public Function<Order, Notification> processOrder() {
return order -> {
System.out.println('Processing: ' + order.getId());
return new Notification(
'Order ' + order.getId() + ' confirmed');
};
}
}
// Consumer
@Configuration
public class NotificationSender {
@Bean
public Consumer<Notification> sendNotification() {
return notification -> {
System.out.println('Sending: ' + notification.getMessage());
};
}
}
// Switch between Kafka and RabbitMQ with config only:
// Change spring.cloud.stream.default-binder: kafka|rabbit
// Benefits of Spring Cloud Stream:
// 1. Broker agnostic - switch easily
// 2. Functional programming model
// 3. Testable - easy mocking
// 4. Built-in error handling
// 5. Dead letter queue support
// Partitioning for parallel processing
spring:
cloud:
stream:
bindings:
input:
consumer:
partitioned: true
instanceCount: 3
instanceIndex: 0Spring Cloud Stream:
Abstraction layer बनाता है:
- Same code काम करे Kafka या RabbitMQ दोनों पर
- Configuration से broker switch कर सकते हो
Programming Model:
1. Supplier (Producer) - emit करना
2. Function (Processor) - transform करना
3. Consumer - consume करना
Usage:
@Bean
public Supplier<Message> supply() {
return () -> new Message();
}
@Bean
public Function<Input, Output> process() {
return input -> transform(input);
}
@Bean
public Consumer<Message> consume() {
return msg -> handle(msg);
}
Benefit: Easy switching between brokers
No code change, only configurationWas this answer clear?