1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
6 import org.apache.kafka.clients.consumer.ConsumerRecords;
7 import org.apache.kafka.clients.consumer.KafkaConsumer;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.WakeupException;
10 import org.apache.kafka.common.serialization.StringDeserializer;
12 import javax.annotation.PreDestroy;
13 import java.time.Duration;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.ExecutorService;
17 import java.util.concurrent.Future;
18 import java.util.concurrent.atomic.AtomicBoolean;
22 public class EndlessConsumer implements Runnable
24 private final ExecutorService executor;
25 private final PartitionStatisticsRepository repository;
26 private final String bootstrapServer;
27 private final String groupId;
28 private final String id;
29 private final String topic;
30 private final String autoOffsetReset;
32 private AtomicBoolean running = new AtomicBoolean();
33 private long consumed = 0;
34 private KafkaConsumer<String, String> consumer = null;
35 private Future<?> future = null;
37 private final Map<Integer, Map<String, Integer>> seen = new HashMap<>();
40 public EndlessConsumer(
41 ExecutorService executor,
42 PartitionStatisticsRepository repository,
43 String bootstrapServer,
47 String autoOffsetReset)
49 this.executor = executor;
50 this.repository = repository;
51 this.bootstrapServer = bootstrapServer;
52 this.groupId = groupId;
55 this.autoOffsetReset = autoOffsetReset;
63 Properties props = new Properties();
64 props.put("bootstrap.servers", bootstrapServer);
65 props.put("group.id", groupId);
66 props.put("client.id", id);
67 props.put("auto.offset.reset", autoOffsetReset);
68 props.put("metadata.max.age.ms", "1000");
69 props.put("key.deserializer", StringDeserializer.class.getName());
70 props.put("value.deserializer", StringDeserializer.class.getName());
72 this.consumer = new KafkaConsumer<>(props);
74 log.info("{} - Subscribing to topic {}", id, topic);
75 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
78 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
80 partitions.forEach(tp ->
82 log.info("{} - removing partition: {}", id, tp);
83 Map<String, Integer> removed = seen.remove(tp.partition());
84 for (String key : removed.keySet())
87 "{} - Seen {} messages for partition={}|key={}",
93 repository.save(new StatisticsDocument(tp.partition(), removed));
98 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
100 partitions.forEach(tp ->
102 log.info("{} - adding partition: {}", id, tp);
106 .findById(Integer.toString(tp.partition()))
107 .map(document -> document.statistics)
108 .orElse(new HashMap<>()));
115 ConsumerRecords<String, String> records =
116 consumer.poll(Duration.ofSeconds(1));
118 // Do something with the data...
119 log.info("{} - Received {} messages", id, records.count());
120 for (ConsumerRecord<String, String> record : records)
124 "{} - {}: {}/{} - {}={}",
133 Integer partition = record.partition();
134 String key = record.key() == null ? "NULL" : record.key();
135 Map<String, Integer> byKey = seen.get(partition);
137 if (!byKey.containsKey(key))
140 int seenByKey = byKey.get(key);
142 byKey.put(key, seenByKey);
146 catch(WakeupException e)
148 log.info("{} - RIIING!", id);
152 log.error("{} - Unexpected error: {}", id, e.toString(), e);
153 running.set(false); // Mark the instance as not running
157 log.info("{} - Closing the KafkaConsumer", id);
159 log.info("{} - Consumer-Thread exiting", id);
163 public Map<Integer, Map<String, Integer>> getSeen()
168 public synchronized void start()
170 boolean stateChanged = running.compareAndSet(false, true);
172 throw new RuntimeException("Consumer instance " + id + " is already running!");
174 log.info("{} - Starting - consumed {} messages before", id, consumed);
175 future = executor.submit(this);
178 public synchronized void stop() throws ExecutionException, InterruptedException
180 boolean stateChanged = running.compareAndSet(true, false);
182 throw new RuntimeException("Consumer instance " + id + " is not running!");
184 log.info("{} - Stopping", id);
187 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
191 public void destroy() throws ExecutionException, InterruptedException
193 log.info("{} - Destroy!", id);
198 catch (IllegalStateException e)
200 log.info("{} - Was already stopped", id);
204 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);