Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application.
In order to learn how to create a spring boot project, refer to this article.
The full-form of JSON is JavaScript Object Notation. JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. Though it is derived from a subset of JavaScript, yet it is Language independent. It is a complete language-independent text format. The following steps can be followed in order to publish JSON messages to Apache Kafka:
- Go to spring initializr and create a starter project with following dependencies:
- Spring Web
- Spring for Apache Kafka
- Open the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and create getters and setters. The following is the implementation of the student class:
// Java program to implement a// student class// Creating a student classpublicclassStudent {// Data members of the// student classintid;String firstName;String lastName;// Constructor of the student// classpublicStudent(intid, String firstName,String lastName){this.id = id;this.firstName = firstName;this.lastName = lastName;}// Implementing the getters// and setterspublicintgetId(){returnid;}publicvoidsetId(intid){this.id = id;}publicString getFirstName(){returnfirstName;}publicvoidsetFirstName(String firstName){this.firstName = firstName;}publicString getLastName(){returnlastName;}publicvoidsetLastName(String lastName){this.lastName = lastName;}}chevron_rightfilter_none - Now, create a new class Controller with the annotation @RestController. Create a GET API and initialize KafkaTemplate with parameter as string and model class object. The following is the implementation of the controller:
// Java program to implement a// controller@RestController@RequestMapping("gfg")publicclassUserResource {@AutowiredprivateKafkaTemplate<String, Student>kafkaTemplate;privatestaticfinalString TOPIC="StudentExample";@GetMapping("/publish/{id}/"+"{firstName}/{lastName}")publicString post(@PathVariable("id")finalintid,@PathVariable("firstName")finalString firstName,@PathVariable("lastName")finalString lastName){kafkaTemplate.send(TOPIC,newStudent(id, firstName,lastName));return"Published successfully";}}chevron_rightfilter_none - Create a class StudentConfig with the annotation @Configuration. In this class we will serialize the object of the model class.
// Java program to serialize the// object of the model class@ConfigurationpublicclassStudentConfig {@BeanpublicProducerFactory<String, Student>producerFactory(){// Create a map of a string// and objectMap<String, Object> config=newHashMap<>();config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"127.0.0.1:9092");config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,StringSerializer.class);config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,JsonSerializer.class);returnnewDefaultKafkaProducerFactory<>(config);}@BeanpublicKafkaTemplate<String, Student>kafkaTemplate(){returnnewKafkaTemplate<>(producerFactory());}}chevron_rightfilter_none - Now, start zookeeper and Kafka server. We need to create a new topic with the name StudentExample. To do so, open a new command prompt window and change directory to the Kafka folder.
- Now, create a new topic using the command given below:
For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name
For Windows: .\bin\windows\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name
- Now to see the messages on the Kafka server in the real-time, use the command below:
For Mac and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginning
For Windows: .\bin\windows\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginning
- Run the application and call the API as:
localhost:8080/gfg/publish/{id}/{first name}/{last name}
Note: If a different port has been used, then replace the port with 8080.
Output:
Recommended Posts:
- Spring Boot | How to publish String messages on Apache Kafka
- Spring Boot | How to consume JSON messages using Apache Kafka
- Spring Boot | How to consume string messages using Apache Kafka
- Spring Boot | How to access database using Spring Data JPA
- Difference Between Apache Kafka and Apache Flume
- Introduction to Spring Boot
- Apache Kafka | Introduction
- Why Apache Kafka is so Fast?
- How to create a REST API using Java Spring Boot
- How to Install and Run Apache Kafka on Windows?
- How to create a basic application in Java Spring Boot
- How to encrypt passwords in a Spring Boot project using Jasypt
- Containerizing Java applications | Creating a Spring Boot App using Dockerfile
- How to convert JSON string to array of JSON objects using JavaScript ?
- JSON | modify an array value of a JSON object
- Difference between Apache Tomcat server and Apache web server
- Custom Messages in ElectronJS
- Send unlimited Whatsapp messages using JavaScript
- Spring MVC with JSP View
- How to print debug messages in the Google Chrome JavaScript Console?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



