![]() |
VOOZH | about |
Subscribing to a Kafka topic from a Java application requires setting up a Kafka consumer that reads messages from a specific topic. This is a key part of many microservice architectures where services must process messages asynchronously. Apache Kafka provides a robust and scalable platform for building such message-driven applications.
Kafka consumers are responsible for reading messages from Kafka topics. The customer subscribes to the topic and always polls for new messages. The key components involved in setting up a Kafka consumer include:
Below are the implementation steps to subscribe to the topic in Apache Kafka from the Java application.
Refer to this link to confirm that Kafka is installed and running on your local system.
Create the Spring Boot project using the Spring Initializr and add the below required dependencies.
After completing this step, the project structure will be like below:
Open the application.properties and add the below properties for configuration of the server port.
spring.application.name=kafka-demo
server.port=8080Now, we will create the KafkaConsumerConfig class that can configure the configuration of the Consumer service.
Go to src > main > java > org.example.kafkademo > KafkaConsumerConfig and put the below code.
Open the main class to subscribe the topic of the Kafka in the Spring application.
Go to src > main > java > org.example.kafkademo > KafkaDemoApplication and put the below code.
pom.xml:
After completing all the above steps, now run the application and it will start at port 8080.
Now, we will use the Kafka producer to send the messages to the topic for testing. We can use the below Kafka command line tool.
.\bin\windows\kafka-topics.bat --create --topic kafka-topic --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1bin/kafka-console-producer.bat --broker-list localhost:9092 --topic kafka-topic
>hello kafka messageBy the following these steps, we can set up the Kafka consumer in the Spring Boot application and it allows microservices to process messages asynchronously and efficiently.