Spring Boot Kafka Microservices - #13 - Create Kafka Consumer in StockService Microservice


Welcome to Spring Boot Kafka Event-Driven Microservices Series. In this lecture, we will Create Kafka Consumer in StockService Microservice.

Lecture  - #13 - Create Kafka Consumer in StockService Microservice


Source Code used in Lecture for Your Reference

Create Kafka Consumer in StockService Microservice

Let's create a Kafka Consumer to receive JSON messages from the topic. 

In a stock-service project, create a package named Kafka. Within a Kafka package, create a class named OrderConsumer and add the following content to it:

package net.javaguides.stockservice.kafka;

import net.javaguides.basedomains.dto.OrderEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

@Service
public class OrderConsumer {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderConsumer.class);

    @KafkaListener(
            topics = "${spring.kafka.topic.name}"
            ,groupId = "${spring.kafka.consumer.group-id}"
    )
    public void consume(OrderEvent event){
        LOGGER.info(String.format("Order event received in stock service => %s", event.toString()));

        // save the order event into the database
    }
}
Note that we are using @KafkaListener annotation to receive messages/events from the Kafka topic.


Comments