1

I followed this article to build a simple Java Spring Boot application to work with Apache Kafka.

Defined the Producer controller as mentioned below

@RestController
@RequestMapping(value = "/kafka")
public class KafkaController {

    private final Producer producer;

    @Autowired
    KafkaController(Producer producer) {
        this.producer = producer;
    }

    @PostMapping(value = "/publish")
    public void sendMessageToKafkaTopic(@RequestParam("message") String message) {
        this.producer.sendMessage(message);
    }
}

and Producer service as below

@Service
public class Producer {

    private static final Logger logger = LoggerFactory.getLogger(Producer.class);
    private static final String TOPIC = "users";

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void sendMessage(String message) {
        logger.info(String.format("#### -> Producing message -> %s", message));
        this.kafkaTemplate.send(TOPIC, message);
    }
}

Consumer Service as mentioned below

@Service
public class Consumer {

    private final Logger logger = LoggerFactory.getLogger(Producer.class);

    @KafkaListener(topics = "users", groupId = "group_id")
    public void consume(String message) throws IOException {
        logger.info(String.format("#### -> Consumed message -> %s", message));
    }
}

and the configuration as shown below

server:
  port: 9000
spring:
  kafka:
    consumer:
      bootstrap-servers: localhost:9092
      group-id: group_id
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
    producer:
      bootstrap-servers: localhost:9092
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer

it works as expected

enter image description here

and prints the message on the console

enter image description here

I want to have a REST API based consumer instead of just printing the messages on the console. How do I do this?

One Developer
  • 99
  • 5
  • 43
  • 103
  • It's not clear what you mean by "REST API based consumer". If you mean you want to consume some record(s) from a REST request, see [this answer](https://stackoverflow.com/questions/64759726/how-to-read-a-message-from-kafka-topic-on-demand/64770164#64770164). – Gary Russell Nov 11 '20 at 14:02
  • Yes, I need an endpoint which would retrieve the latest record/message from the topic. I did go through the link provided. Can you please let me know how to convert the code so that I will have an Rest endpoint to retrieve the message /record. I am a newbie to java. – One Developer Nov 11 '20 at 17:43

1 Answers1

1

See How to read a message from Kafka topic on demand

Just put the code (starting with the try) in a @GetMapping method.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179