How to Send Message Using Kafka with Spring Boot
To send a message using
KafkaTemplate in Spring, inject it into your service and call send(topic, message). Configure Kafka properties in application.properties and create a producer bean if needed.Syntax
The main part to send a message in Spring Kafka is using KafkaTemplate<String, String>. You call send() with the topic name and the message content.
KafkaTemplate: Spring's helper to send messages.send(topic, message): Sends the message to the Kafka topic.- Topic: The name of the Kafka channel where messages go.
- Message: The string or object you want to send.
java
kafkaTemplate.send("my-topic", "Hello Kafka!");
Example
This example shows a simple Spring Boot application that sends a message to Kafka when the app runs.
java
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.context.annotation.Bean; @SpringBootApplication public class KafkaSenderApplication { public static void main(String[] args) { SpringApplication.run(KafkaSenderApplication.class, args); } @Bean public CommandLineRunner sendMessage(KafkaTemplate<String, String> kafkaTemplate) { return args -> { kafkaTemplate.send("my-topic", "Hello Kafka from Spring Boot!"); System.out.println("Message sent to Kafka topic 'my-topic'"); }; } }
Output
Message sent to Kafka topic 'my-topic'
Common Pitfalls
Common mistakes when sending Kafka messages in Spring include:
- Not configuring Kafka broker address in
application.properties. - Forgetting to create or inject
KafkaTemplate. - Using the wrong topic name or misspelling it.
- Not handling exceptions or checking if the message was sent successfully.
Always verify your Kafka server is running and reachable.
java
/* Wrong: No KafkaTemplate injected */ public void sendMessage(String msg) { kafkaTemplate.send("topic", msg); // kafkaTemplate is null } /* Right: Inject KafkaTemplate via constructor or @Autowired */ private final KafkaTemplate<String, String> kafkaTemplate; public MyService(KafkaTemplate<String, String> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } public void sendMessage(String msg) { kafkaTemplate.send("topic", msg); }
Quick Reference
Remember these key points when sending messages with Spring Kafka:
- Configure
spring.kafka.bootstrap-serversinapplication.properties. - Use
KafkaTemplate<String, String>to send messages. - Call
send(topic, message)to publish. - Handle exceptions or use callbacks for delivery confirmation.
Key Takeaways
Inject and use KafkaTemplate to send messages in Spring.
Configure Kafka broker address in application.properties.
Always specify the correct topic name when sending.
Handle exceptions or use callbacks to confirm message delivery.
Ensure Kafka server is running and accessible before sending.