BlogNote

A Blog to Share Information

Spring Boot Kafka Producer & Consumer Example

You need to start with the following read:

Run Kafka with KafkaUI to Test Kafka Listener Locally

Or start Kafka broker on localhost:9092.

Creating message producer project with Spring Initializr.

Add properties to application.properties file:

server.port=8788
spring.application.name=kafkaproducer
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup

Add service interface:

package com.ergulcu.kafkaproducer.service;

public interface MessageService {
    void sendMessage(String message);
}

Add service implementation:

@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {
    private final KafkaTemplate kafkaTemplate;
    @Override
    public void sendMessage(String message){
        kafkaTemplate.send("TestTopic", message);
    }
}

Add controller:

package com.ergulcu.kafkaproducer.controller;

import com.ergulcu.kafkaproducer.service.MessageService;
lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class MessageController {
    private final MessageService messageService;
    @PostMapping("/message")
    public void postMessage(@RequestBody String message){
        messageService.sendMessage(message);
    }
}

Creating message consumer project with Spring Initializr.

Add properties to application.properties file:

server.port=8787
spring.application.name=kafkaconsumer
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup

Add service interface:

package com.ergulcu.kafkaconsumer.service;

public interface MessageService {
}

Add service implementation:

package com.ergulcu.kafkaconsumer.service.impl;

import com.ergulcu.kafkaconsumer.service.MessageService;
lombok.RequiredArgsConstructor;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {
    @KafkaListener(topics = "TestTopic",groupId = "TestGroup")
    public void listenGroupFoo(String message) {
        System.out.println("Received Message from TestTopic:" + message);
    }
}

Send message to producer with Postman:

endpoint: localhost:8787/message
request body: testing message {{$randomWord}} {{$isoTimestamp}}

See messages on consumer console:

Ready to run projects if you want to try directly:

https://github.com/ergulcu/kafkaconsumer

https://github.com/ergulcu/kafkaproducer