Spring Boot | How to consume string messages using Apache Kafka
Last Updated :
04 Jul, 2022
Apache Kafka is a publish-subscribe messaging queue used for real-time streams of data. A messaging queue lets you send messages between processes, applications, and servers. In this article we will see how to send string messages from apache kafka to the console of a spring boot application.
Approach:
Step 1: Go to spring initializr and create a starter project with following dependency:

Note: We can also create a maven project and add the following code to pom.xml file.
Xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Step 2: Open the project in an IDE and sync the dependencies. Now create a new class Config and add annotations @Configuration and @EnableKafka.

Step 3: Now create beans ConsumerFactory and ConcurrentKafkaListenerContainerFactory with String object.
Java
// Java program to consume string
// messages using spring kafka
@EnableKafka
@Configuration
public class Config {
// Function to establish
// connection between spring
// application and kafka server
@Bean
public ConsumerFactory<String, String>
consumerFactory()
{
// HashMap to store the configurations
Map<String, Object> map = new HashMap<>();
// put the host IP in the map
map.put(ConsumerConfig
.BOOTSTRAP_SERVERS_CONFIG,
"127.0.0.1:9092");
// put the group ID in the map
map.put(ConsumerConfig
.GROUP_ID_CONFIG,
"id");
map.put(ConsumerConfig
.KEY_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class);
map.put(ConsumerConfig
.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class);
return new DefaultKafkaConsumerFactory<>(map);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String,
String>
kafkaListner()
{
ConcurrentKafkaListenerContainerFactory<String,
String>
obj
= new ConcurrentKafkaListenerContainerFactory<>();
obj.setConsumerFactory(consumerFactory());
return obj;
}
}
Step 4: Create a class KafkaService with @Service annotation. This class will contain the listener method to publish the message on the console.
Java
@Service
public class KafkaService {
// Annotation required to listen the
// message from kafka server
@KafkaListener(topics = "StringProducer",
groupId = "id")
public void
publish(String message)
{
System.out.println(
"You have a new message: "
+ message);
}
}
Step 5: Start zookeeper and then kafka server using the command below.
For windows:
.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties
.\bin\windows\kafka-server-start.bat .\config\server.properties
For mac and linux:
bin/zookeeper-server-start.sh config/zookeeper.properties
bin/kafka-server-start.sh config/server.properties
Step 6: Now we need to create a new topic with the name StringProducer. To do so, open a new command prompt window and change directory to the kafka directory. 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
Step 7: Now to run kafka producer console, use the command below:
// For Mac and Linux
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Kafka_Example
// For Windows
.\bin\windows\kafka-console-producer.bat --broker-list localhost:9092 --topic Kafka_Example
Step 7: Run the application and type message on kafka producer and press enter.
Output:

Here type a message in string format on kafka producer
>Hello
>Welcome to GeeksForGeeks
Output:

Similar Reads
Dynamic Dropdown From Database using Spring Boot The concept of dynamic dropdown (or dependent dropdown) is exciting and challenging to code. Dynamic dropdown means that the values in one dropdown list are dependent on the value selected in the previous dropdown list. A simple example would be three dropdown boxes displaying names of the district,
11 min read
Spring - RestTemplate Due to high traffic and quick access to services, REST APIs are getting more popular and have become the backbone of modern web development. It provides quick access to services and also provides fast data exchange between applications. REST is not a protocol or a standard, rather, it is a set of ar
7 min read
Spring Boot - Scheduling Spring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application Implementation:It is depicted below stepwise as follows:Â St
4 min read
Spring Boot - Sending Email via SMTP Spring Boot provides the ability to send emails via SMTP using the JavaMail Library. Here we will be illustrating step-by-step guidelines to develop Restful web services that can be used to send emails with or without attachments. In order to begin with the steps, let us first create a Spring Boot p
5 min read
Different Ways to Establish Communication Between Spring Microservices If you are working with a Spring Boot project which involves multiple microservices, You might have felt the need to communicate from microservice m1 to microservice m2. Depending upon business use-cases, this communication can be of synchronous or asynchronous type. Before digging dip further. Let'
3 min read
JSON using Jackson in REST API Implementation with Spring Boot When we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client.In this article, we are going to learn the approach that is used
4 min read
How to encrypt passwords in a Spring Boot project using Jasypt In this article, we will learn how to encrypt data in Spring Boot application config files like application.properties or application.yml. Inside those files, we can encrypt username, password, etc. You often come across developing projects where you have to connect to databases like MongoDB, etc, a
4 min read
Containerizing Spring Boot Application Java applications, known for their robustness sometimes become difficult to deploy and manage. This is where containerization comes into the picture. Packaging your Java app into a lightweight and self-contained independent unit can provide many benefits to the developers: PortabilityScalabilityFast
3 min read
How to Send Images in Spring Boot without using Servlet and Redundant JSP Codes? Open IntelliJ IDE and in the Controller section of your project inside the Controller class you need to build the Image serve method. The Image serve method looks like below and as you have to collect the Image response use @GetMapping Annotation to collect the image. ImageHandler Controller Method
2 min read
How to Create Todo List API using Spring Boot and MySQL? Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
6 min read