Interview question
What are Publish-Subscribe (Pub-Sub) patterns in Spring Boot? Spring Boot में Publish-Subscribe (Pub-Sub) patterns क्या हैं?
Answer
Pub-Sub is a messaging pattern where publishers send messages to topics without knowing subscribers, and subscribers receive all messages from subscribed topics. Enables loose coupling and one-to-many communication in distributed systems.
// Spring Cloud Stream Pub-Sub Example
// Publisher
@RestController
@RequestMapping('/api/orders')
public class OrderPublisher {
@Autowired
private StreamBridge streamBridge;
@PostMapping
public void createOrder(@RequestBody Order order) {
// Publish to 'order-events' destination
streamBridge.send('order-events', order);
}
}
// Subscriber 1: Inventory Service
@Service
public class InventoryService {
@Bean
public Consumer<Order> inventoryProcessor() {
return order -> {
System.out.println('Updating inventory for order: ' +
order.getId());
// Update inventory
};
}
}
// Subscriber 2: Notification Service
@Service
public class NotificationService {
@Bean
public Consumer<Order> notificationProcessor() {
return order -> {
System.out.println('Sending notification for order: ' +
order.getId());
// Send email/SMS
};
}
}
// Subscriber 3: Analytics Service
@Service
public class AnalyticsService {
@Bean
public Consumer<Order> analyticsProcessor() {
return order -> {
System.out.println('Recording order metric: ' +
order.getId());
// Log metrics
};
}
}
// Configuration
spring:
cloud:
function:
definition: inventoryProcessor;notificationProcessor;analyticsProcessor
stream:
bindings:
inventoryProcessor-in-0:
destination: order-events
group: inventory-group
notificationProcessor-in-0:
destination: order-events
group: notification-group
analyticsProcessor-in-0:
destination: order-events
group: analytics-group
// Pub-Sub guarantees:
// 1. Fan-out - single message to multiple subscribers
// 2. Loose coupling - publishers don't know subscribers
// 3. Scalability - add subscribers without changing publisher
// 4. Independent processing - each subscriber own pace
// 5. Message durability - queue persistencePub-Sub Pattern:
Publisher: Order service message publish करता है
Subscribers: Multiple services सुनते हैं
Benefit:
- Loose coupling
- Scalability
- Multiple consumers
- Independent processing
Implementation:
StreamBridge से send करना
Consumer से receive करना
Configuration:
Destination - topic name
Group - consumer group
Binding - connection setup
Example:
Order created -> Inventory update
-> Notification send
-> Analytics log
सभी independently process हो रहे हैंWas this answer clear?