Spring Boot Kafka Producer and Consumer Example
2 min readAug 9, 2024
You need to start with following read
https://medium.com/@ergulcu/kafka-with-kafkaui-to-test-kafka-listener-localy-65e3d556854b
or start kafka broker on localhost:9092
creating message producer project with spring initializer
add properties to application.properties file
add service
package com.ergulcu.kafkaproducer.service;
public interface MessageService {
void sendMessage(String message);
}
add service impl
@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {
private final KafkaTemplate<String, String> kafkaTemplate;
@Override
public void sendMessage(String message){
kafkaTemplate.send("TestTopic", message);
}
}
add controller
package com.ergulcu.kafkaproducer.controller;
import com.ergulcu.kafkaproducer.service.MessageService;
import 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 initializer
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
package com.ergulcu.kafkaconsumer.service;
public interface MessageService {
}
add service impl
package com.ergulcu.kafkaconsumer.service.impl;
import com.ergulcu.kafkaconsumer.service.MessageService;
import 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