Spring Boot — publish Kafka messages

3 min readJun 3, 2022

In this article, we’ll take a look at how to send messages to a Kafka topic using a REST application. We’ll also look at how to serialize an object so we can send it as a message. Be sure to have Kafka running as this article will not go into how to set that up.

New project

Below are the dependencies I’m using.


The producer is what we’ll use to send messages to a Kafka topic. When setting up the producer, we’ll define how the key and value of our message should be serialized.

Let’s add a config class and add the following to it.

With a String serializer for the key and value, we’re defining that we want to send string values for both key and value. We’ve also defined that our bootstrap server is running on localhost port 9092. Change this to whatever port you have Kafka broker running.

Next, let’s create a class that will let us send messages to any topic as long as the key and value are of the same type as the ones we defined in our KafkaProducerConfig class.

With this, we’ll be able to send messages to any of the topics defined above.

Send test message

To test sending messages, we’ll add a controller with one endpoint. We’ll autowire the KafkaProducer class we created.

Let’s make a post request with a test message

And in Kafkdrop we can see that our message was successfully sent and is in the topic.


Software Engineer, London