Spring Boot Kafka Json Serializer Example, easy in 15 minutes

Today, I introduce a Spring Boot Kafka Json Serializer Example and demo how to send and receive a Java Object as JSON object from Apache Kafka using Spring-Kafka and Spring Boot. I make sure that this tutorial is useful with a real project. Let’ do together.

Spring Boot Kafka Json Serializer Example

Project Setup

  • Spring Kafka: 2.3.4.RELEASE
  • Spring Boot: 2.2.2.RELEASE
  • Apache Kafka: kafka_2.13-2.4.0
  • Maven: 3.5

Project Structure

Spring Boot Kafka Json Serializer Example

Maven Dependencies

At least, we must have these dependencies: spring-boot-starter, spring-kafka, jackson-databind in pom.xml file. Note, you can change spring-kafka version for your own needs.

Configure Spring Kafka Application with application.yml

Some properties that need to be explicitly set in the application.yml file, e.g host, port, topic name:

Simple POJO to Serialize/Deserialize

We do with simple POJO class named Staff, its object will be serialized/deserialized to java object/json object.

Using Jackson to Serialize/Deserialize

Here, we create two classes to custom Serialize/Deserialize for the birthday field.

Create Kafka Producer and Consumer

If you want to understand deeply how to create Producer and Consumer with configuration, please the post Spring Boot Kafka Producer Consumer Configuration  or You can also create Spring Boot Kafka Producer and Consumer without configuration, let check out the post Spring Boot Apache Kafka Example. Here I just introduce java source code for demonstration purposes.

Sending Kafka Messages to Topic

Here is the Spring Boot Kafka Producer configuration.

Receiving Kafka Messages from Topic

Here is the Spring Boot Kafka Consumer configuration:

Spring Boot Application

To demo our Spring Boot Kafka Json Serializer Example then we create a simple Spring Boot Application below.

Running Spring Boot Application

Just run Spring Boot Application normally, it will print the output below

That’s all about Spring Boot Kafka Json Serializer Example. Now you can try to do your own practices and don’t forget to download the complete source code of Spring Boot Kafka Json Serializer Example below.

Download the complete source code

spring-kafka-json-serializer-deserializer-example.zip (86 downloads)

References

Spring Boot Kafka Producer Consumer Configuration
Spring Boot Apache Kafka Example
Spring Kafka Serialize Deserialize Documentation

Please share it if you found this useful
Hide Buttons