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.Clock;
12 import java.time.Duration;
13 import java.time.Instant;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.ExecutorService;
17 import java.util.concurrent.locks.Condition;
18 import java.util.concurrent.locks.Lock;
19 import java.util.concurrent.locks.ReentrantLock;
23 @RequiredArgsConstructor
24 public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnable
26 private final ExecutorService executor;
27 private final PartitionStatisticsRepository repository;
28 private final String id;
29 private final String topic;
30 private final Clock clock;
31 private final Duration commitInterval;
32 private final Consumer<K, V> consumer;
33 private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
35 private final Lock lock = new ReentrantLock();
36 private final Condition condition = lock.newCondition();
37 private boolean running = false;
38 private Exception exception;
39 private long consumed = 0;
41 private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
45 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
47 partitions.forEach(tp ->
49 Integer partition = tp.partition();
50 Long newOffset = consumer.position(tp);
52 "{} - removing partition: {}, offset of next message {})",
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, consumer.position(tp)));
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 StatisticsDocument document =
80 .findById(Integer.toString(partition))
81 .orElse(new StatisticsDocument(partition));
82 if (document.offset >= 0)
84 // Only seek, if a stored offset was found
85 // Otherwise: Use initial offset, generated by Kafka
86 consumer.seek(tp, document.offset);
88 seen.put(partition, document.statistics);
98 log.info("{} - Subscribing to topic {}", id, topic);
99 consumer.subscribe(Arrays.asList(topic), this);
101 Instant lastCommit = clock.instant();
105 ConsumerRecords<K, V> records =
106 consumer.poll(Duration.ofSeconds(1));
108 // Do something with the data...
109 log.info("{} - Received {} messages", id, records.count());
110 for (ConsumerRecord<K, V> record : records)
113 "{} - {}: {}/{} - {}={}",
122 handler.accept(record);
126 Integer partition = record.partition();
127 String key = record.key() == null ? "NULL" : record.key().toString();
128 Map<String, Long> byKey = seen.get(partition);
130 if (!byKey.containsKey(key))
133 long seenByKey = byKey.get(key);
135 byKey.put(key, seenByKey);
138 if (lastCommit.plus(commitInterval).isBefore(clock.instant()))
140 log.debug("Storing data and offsets, last commit: {}", lastCommit);
141 seen.forEach((partiton, statistics) -> repository.save(
142 new StatisticsDocument(
145 consumer.position(new TopicPartition(topic, partiton)))));
146 lastCommit = clock.instant();
150 catch(WakeupException e)
152 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
155 catch(RecordDeserializationException e)
157 TopicPartition tp = e.topicPartition();
158 long offset = e.offset();
160 "{} - Could not deserialize message on topic {} with offset={}: {}",
164 e.getCause().toString());
170 log.error("{} - Unexpected error: {}", id, e.toString(), e);
175 log.info("{} - Consumer-Thread exiting", id);
179 private void shutdown()
184 private void shutdown(Exception e)
191 log.info("{} - Unsubscribing from topic {}", id, topic);
192 consumer.unsubscribe();
197 "{} - Error while unsubscribing from topic {}: {}",
215 public Map<Integer, Map<String, Long>> getSeen()
226 throw new IllegalStateException("Consumer instance " + id + " is already running!");
228 log.info("{} - Starting - consumed {} messages before", id, consumed);
231 executor.submit(this);
239 public synchronized void stop() throws ExecutionException, InterruptedException
245 throw new IllegalStateException("Consumer instance " + id + " is not running!");
247 log.info("{} - Stopping", id);
250 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
259 public void destroy() throws ExecutionException, InterruptedException
261 log.info("{} - Destroy!", id);
262 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);