Video in progress
How do you send a message to Kafka from a Spring Boot application?
Once you add spring-kafka, Spring Boot creates a KafkaTemplate automatically. You inject it and call send(topic, key, value); the result comes back as a CompletableFuture.
📖 Answer
@Service
@RequiredArgsConstructor
public class OrderPublisher {
private final KafkaTemplate<String, OrderCreated> kafkaTemplate;
public void publish(OrderCreated event) {
kafkaTemplate.send("orders", event.orderId(), event)
.whenComplete((result, ex) -> {
if (ex != null) {
log.error("Yuborilmadi: {}", event.orderId(), ex);
} else {
log.debug("Yozildi offset={}", result.getRecordMetadata().offset());
}
});
}
}
send is asynchronous: when the method returns, the message may not have reached the broker yet; it's sitting in the producer buffer. If you don't check the result, the error is silently swallowed.
In Spring Kafka 3.x send returns a CompletableFuture; in 2.x it was a ListenableFuture, which is why you see addCallback in older code.
Serializers are set in application.yml: key-serializer and value-serializer.
Sign up to mark studied questions and save your progress.