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 String id;
26 private final String topic;
27 private final Consumer<K, V> consumer;
28 private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
30 private final Lock lock = new ReentrantLock();
31 private final Condition condition = lock.newCondition();
32 private boolean running = false;
33 private Exception exception;
34 private long consumed = 0;
36 private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
37 private final Map<Integer, Long> offsets = new HashMap<>();
41 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
43 partitions.forEach(tp ->
45 Integer partition = tp.partition();
46 Long newOffset = consumer.position(tp);
47 Long oldOffset = offsets.remove(partition);
49 "{} - removing partition: {}, consumed {} records (offset {} -> {})",
52 newOffset - oldOffset,
55 Map<String, Long> removed = seen.remove(partition);
56 for (String key : removed.keySet())
59 "{} - Seen {} messages for partition={}|key={}",
69 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
71 partitions.forEach(tp ->
73 Integer partition = tp.partition();
74 Long offset = consumer.position(tp);
75 log.info("{} - adding partition: {}, offset={}", id, partition, offset);
76 offsets.put(partition, offset);
77 seen.put(partition, new HashMap<>());
87 log.info("{} - Subscribing to topic {}", id, topic);
88 consumer.subscribe(Arrays.asList(topic), this);
92 ConsumerRecords<K, V> records =
93 consumer.poll(Duration.ofSeconds(1));
95 // Do something with the data...
96 log.info("{} - Received {} messages", id, records.count());
97 for (ConsumerRecord<K, V> record : records)
100 "{} - {}: {}/{} - {}={}",
109 handler.accept(record);
113 Integer partition = record.partition();
114 String key = record.key() == null ? "NULL" : record.key().toString();
115 Map<String, Long> byKey = seen.get(partition);
117 if (!byKey.containsKey(key))
120 long seenByKey = byKey.get(key);
122 byKey.put(key, seenByKey);
126 catch(WakeupException e)
128 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
129 consumer.commitSync();
132 catch(RecordDeserializationException e)
134 TopicPartition tp = e.topicPartition();
135 long offset = e.offset();
137 "{} - Could not deserialize message on topic {} with offset={}: {}",
141 e.getCause().toString());
143 consumer.commitSync();
148 log.error("{} - Unexpected error: {}", id, e.toString(), e);
153 log.info("{} - Consumer-Thread exiting", id);
157 private void shutdown()
162 private void shutdown(Exception e)
169 log.info("{} - Unsubscribing from topic {}", id, topic);
170 consumer.unsubscribe();
175 "{} - Error while unsubscribing from topic {}: {}",
193 public Map<Integer, Map<String, Long>> getSeen()
204 throw new IllegalStateException("Consumer instance " + id + " is already running!");
206 log.info("{} - Starting - consumed {} messages before", id, consumed);
209 executor.submit(this);
217 public synchronized void stop() throws ExecutionException, InterruptedException
223 throw new IllegalStateException("Consumer instance " + id + " is not running!");
225 log.info("{} - Stopping", id);
228 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
237 public void destroy() throws ExecutionException, InterruptedException
239 log.info("{} - Destroy!", id);
244 catch (IllegalStateException e)
246 log.info("{} - Was already stopped", id);
250 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
254 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
258 public boolean running()
271 public Optional<Exception> exitStatus()
277 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
279 return Optional.ofNullable(exception);