1 package de.juplo.kafka;
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.*;
6 import org.apache.kafka.common.TopicPartition;
7 import org.apache.kafka.common.errors.RecordDeserializationException;
8 import org.apache.kafka.common.errors.WakeupException;
10 import javax.annotation.PreDestroy;
11 import java.time.Duration;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.ExecutorService;
15 import java.util.concurrent.locks.Condition;
16 import java.util.concurrent.locks.Lock;
17 import java.util.concurrent.locks.ReentrantLock;
21 @RequiredArgsConstructor
22 public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnable
24 private final ExecutorService executor;
25 private final PartitionStatisticsRepository repository;
26 private final String id;
27 private final String topic;
28 private final Consumer<K, V> consumer;
29 private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
31 private final Lock lock = new ReentrantLock();
32 private final Condition condition = lock.newCondition();
33 private boolean running = false;
34 private Exception exception;
35 private long consumed = 0;
37 private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
38 private final Map<Integer, Long> offsets = new HashMap<>();
42 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
44 partitions.forEach(tp ->
46 Integer partition = tp.partition();
47 Long newOffset = consumer.position(tp);
48 Long oldOffset = offsets.remove(partition);
50 "{} - removing partition: {}, consumed {} records (offset {} -> {})",
53 newOffset - oldOffset,
56 Map<String, Long> removed = seen.remove(partition);
57 for (String key : removed.keySet())
60 "{} - Seen {} messages for partition={}|key={}",
66 repository.save(new StatisticsDocument(partition, removed));
71 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
73 partitions.forEach(tp ->
75 Integer partition = tp.partition();
76 Long offset = consumer.position(tp);
77 log.info("{} - adding partition: {}, offset={}", id, partition, offset);
78 offsets.put(partition, offset);
82 .findById(Integer.toString(tp.partition()))
83 .map(document -> document.statistics)
84 .orElse(new HashMap<>()));
94 log.info("{} - Subscribing to topic {}", id, topic);
95 consumer.subscribe(Arrays.asList(topic), this);
99 ConsumerRecords<K, V> records =
100 consumer.poll(Duration.ofSeconds(1));
102 // Do something with the data...
103 log.info("{} - Received {} messages", id, records.count());
104 for (ConsumerRecord<K, V> record : records)
107 "{} - {}: {}/{} - {}={}",
116 handler.accept(record);
120 Integer partition = record.partition();
121 String key = record.key() == null ? "NULL" : record.key().toString();
122 Map<String, Long> byKey = seen.get(partition);
124 if (!byKey.containsKey(key))
127 long seenByKey = byKey.get(key);
129 byKey.put(key, seenByKey);
133 catch(WakeupException e)
135 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
136 consumer.commitSync();
139 catch(RecordDeserializationException e)
141 TopicPartition tp = e.topicPartition();
142 long offset = e.offset();
144 "{} - Could not deserialize message on topic {} with offset={}: {}",
148 e.getCause().toString());
150 consumer.commitSync();
155 log.error("{} - Unexpected error: {}", id, e.toString(), e);
160 log.info("{} - Consumer-Thread exiting", id);
164 private void shutdown()
169 private void shutdown(Exception e)
176 log.info("{} - Unsubscribing from topic {}", id, topic);
177 consumer.unsubscribe();
182 "{} - Error while unsubscribing from topic {}: {}",
200 public Map<Integer, Map<String, Long>> getSeen()
211 throw new IllegalStateException("Consumer instance " + id + " is already running!");
213 log.info("{} - Starting - consumed {} messages before", id, consumed);
216 executor.submit(this);
224 public synchronized void stop() throws ExecutionException, InterruptedException
230 throw new IllegalStateException("Consumer instance " + id + " is not running!");
232 log.info("{} - Stopping", id);
235 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
244 public void destroy() throws ExecutionException, InterruptedException
246 log.info("{} - Destroy!", id);
251 catch (IllegalStateException e)
253 log.info("{} - Was already stopped", id);
257 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
261 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
265 public boolean running()
278 public Optional<Exception> exitStatus()
284 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
286 return Optional.ofNullable(exception);