1 package de.juplo.kafka;
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.beans.factory.annotation.Value;
8 import org.springframework.kafka.annotation.KafkaListener;
9 import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
10 import org.springframework.stereotype.Component;
12 import java.util.function.Consumer;
17 @RequiredArgsConstructor
18 public class EndlessConsumer<K, V>
21 private KafkaListenerEndpointRegistry registry;
22 @Value("${consumer.client-id}")
25 Consumer<ConsumerRecord<K, V>> handler;
27 private long consumed = 0;
30 id = "${consumer.client-id}",
32 topics = "${consumer.topic}",
33 autoStartup = "false")
34 public void receive(ConsumerRecord<K, V> record)
37 "{} - {}: {}/{} - {}={}",
46 handler.accept(record);
52 public synchronized void start()
54 if (registry.getListenerContainer(id).isChildRunning())
55 throw new IllegalStateException("Consumer instance " + id + " is already running!");
57 log.info("{} - Starting - consumed {} messages before", id, consumed);
58 registry.getListenerContainer(id).start();
61 public synchronized void stop()
63 if (!registry.getListenerContainer(id).isChildRunning())
64 throw new IllegalStateException("Consumer instance " + id + " is not running!");
66 log.info("{} - Stopping", id);
67 registry.getListenerContainer(id).stop();
68 log.info("{} - Stopped - consumed {} messages so far", id, consumed);