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.List;
13 import java.util.function.Consumer;
18 @RequiredArgsConstructor
19 public class EndlessConsumer<K, V>
22 private KafkaListenerEndpointRegistry registry;
23 @Value("${consumer.client-id}")
26 Consumer<ConsumerRecord<K, V>> handler;
28 private long consumed = 0;
31 id = "${consumer.client-id}",
33 topics = "${consumer.topic}",
34 containerFactory = "batchFactory",
35 autoStartup = "false")
36 public void receive(List<ConsumerRecord<K, V>> records)
38 // Do something with the data...
39 log.info("{} - Received {} messages", id, records.size());
40 for (ConsumerRecord<K, V> record : records)
43 "{} - {}: {}/{} - {}={}",
52 handler.accept(record);
59 public synchronized void start()
61 if (registry.getListenerContainer(id).isChildRunning())
62 throw new IllegalStateException("Consumer instance " + id + " is already running!");
64 log.info("{} - Starting - consumed {} messages before", id, consumed);
65 registry.getListenerContainer(id).start();
68 public synchronized void stop()
70 if (!registry.getListenerContainer(id).isChildRunning())
71 throw new IllegalStateException("Consumer instance " + id + " is not running!");
73 log.info("{} - Stopping", id);
74 registry.getListenerContainer(id).stop();
75 log.info("{} - Stopped - consumed {} messages so far", id, consumed);