โ After starting Kafka via Docker (docker-compose up -d), open http://localhost:18080 to access the Kafka UI and create a topic named customer-notification.
Please create topic :
๐ค Kafka Publisher – Customer Service
In this service, we simulate saving a customer (not storing in DB for now), and after that we publish a notification to Kafka.
Even if the notification service is down, Kafka will keep the message and deliver it later when the consumer is up.
@RestController@RequestMapping("/api/customers")@RequiredArgsConstructorpublicclassCustomerController {privatefinalCustomerPublisher customerPublisher; @PostMappingpublicResponseEntity<String> createCustomer(@RequestBodyCustomerResponseDTO customerDto) {// Here you would normally save to DBCustomerNotification notification =CustomerNotification.builder().notificationType("NEW_CUSTOMER").customerResponseDTO(customerDto).message("New customer created").build();customerPublisher.publishCustomerNotification(notification);returnResponseEntity.ok("Customer created and event published to Kafka"); }}
This method listens to the customer-notification topic. Whenever a new message arrives (like a new customer), it logs the message and can take actions (e.g., send an email).
@Component@Log4j2publicclassNotificationConsumer { @KafkaListener(topics ="customer-notification", groupId ="customer-notification-email")publicvoidconsume(CustomerNotification notification) {log.info("Received notification: {}", notification);// Process notification, send email, etc. }}
๐ What If the Notification Service is Down?
If we were calling the notification service using RestTemplate, and the service is down, our customer service would fail or retry. โ
But with Kafka, even if the consumer (notification service) is temporarily down, the event is still sent to Kafka and will be delivered once the consumer is back up. โ
This makes the system more resilient and loosely coupled.
๐ง Sending Emails (Optional Extension)
If you want to send emails from the consumer side:
This is exactly what I was looking for! The integration with Docker made it so easy to test everything locally. Great job explaining each part step by step.
Leave a Reply