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<>();
41 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
43 partitions.forEach(tp ->
45 Integer partition = tp.partition();
46 Long newOffset = consumer.position(tp);
48 "{} - removing partition: {}, offset of next message {})",
52 Map<String, Long> removed = seen.remove(partition);
53 for (String key : removed.keySet())
56 "{} - Seen {} messages for partition={}|key={}",
62 repository.save(new StatisticsDocument(partition, removed, consumer.position(tp)));
67 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
69 partitions.forEach(tp ->
71 Integer partition = tp.partition();
72 Long offset = consumer.position(tp);
73 log.info("{} - adding partition: {}, offset={}", id, partition, offset);
74 StatisticsDocument document =
76 .findById(Integer.toString(partition))
77 .orElse(new StatisticsDocument(partition));
78 consumer.seek(tp, document.offset);
79 seen.put(partition, document.statistics);
89 log.info("{} - Subscribing to topic {}", id, topic);
90 consumer.subscribe(Arrays.asList(topic), this);
94 ConsumerRecords<K, V> records =
95 consumer.poll(Duration.ofSeconds(1));
97 // Do something with the data...
98 log.info("{} - Received {} messages", id, records.count());
99 for (ConsumerRecord<K, V> record : records)
102 "{} - {}: {}/{} - {}={}",
111 handler.accept(record);
115 Integer partition = record.partition();
116 String key = record.key() == null ? "NULL" : record.key().toString();
117 Map<String, Long> byKey = seen.get(partition);
119 if (!byKey.containsKey(key))
122 long seenByKey = byKey.get(key);
124 byKey.put(key, seenByKey);
127 seen.forEach((partiton, statistics) -> repository.save(
128 new StatisticsDocument(
131 consumer.position(new TopicPartition(topic, partiton)))));
134 catch(WakeupException e)
136 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
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());
154 log.error("{} - Unexpected error: {}", id, e.toString(), e);
159 log.info("{} - Consumer-Thread exiting", id);
163 private void shutdown()
168 private void shutdown(Exception e)
175 log.info("{} - Unsubscribing from topic {}", id, topic);
176 consumer.unsubscribe();
181 "{} - Error while unsubscribing from topic {}: {}",
199 public Map<Integer, Map<String, Long>> getSeen()
210 throw new IllegalStateException("Consumer instance " + id + " is already running!");
212 log.info("{} - Starting - consumed {} messages before", id, consumed);
215 executor.submit(this);
223 public synchronized void stop() throws ExecutionException, InterruptedException
229 throw new IllegalStateException("Consumer instance " + id + " is not running!");
231 log.info("{} - Stopping", id);
234 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
243 public void destroy() throws ExecutionException, InterruptedException
245 log.info("{} - Destroy!", id);
246 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
249 public boolean running()
262 public Optional<Exception> exitStatus()
268 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
270 return Optional.ofNullable(exception);