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.WakeupException;
9 import javax.annotation.PreDestroy;
10 import java.time.Duration;
12 import java.util.concurrent.ExecutionException;
13 import java.util.concurrent.ExecutorService;
14 import java.util.concurrent.locks.Condition;
15 import java.util.concurrent.locks.Lock;
16 import java.util.concurrent.locks.ReentrantLock;
20 @RequiredArgsConstructor
21 public class EndlessConsumer implements Runnable
23 private final ExecutorService executor;
24 private final String id;
25 private final String topic;
26 private final Consumer<String, String> consumer;
27 private final java.util.function.Consumer<ConsumerRecord<String, String>> handler;
29 private final Lock lock = new ReentrantLock();
30 private final Condition condition = lock.newCondition();
31 private boolean running = false;
32 private Exception exception;
33 private long consumed = 0;
35 private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
36 private final Map<Integer, Long> offsets = new HashMap<>();
44 log.info("{} - Subscribing to topic {}", id, topic);
45 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
48 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
50 partitions.forEach(tp ->
52 Integer partition = tp.partition();
53 Long newOffset = consumer.position(tp);
54 Long oldOffset = offsets.remove(partition);
56 "{} - removing partition: {}, consumed {} records (offset {} -> {})",
59 newOffset - oldOffset,
62 Map<String, Long> removed = seen.remove(partition);
63 for (String key : removed.keySet())
66 "{} - Seen {} messages for partition={}|key={}",
76 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
78 partitions.forEach(tp ->
80 Integer partition = tp.partition();
81 Long offset = consumer.position(tp);
82 log.info("{} - adding partition: {}, offset={}", id, partition, offset);
83 offsets.put(partition, offset);
84 seen.put(partition, new HashMap<>());
91 ConsumerRecords<String, String> records =
92 consumer.poll(Duration.ofSeconds(1));
94 // Do something with the data...
95 log.info("{} - Received {} messages", id, records.count());
96 for (ConsumerRecord<String, String> record : records)
99 "{} - {}: {}/{} - {}={}",
108 handler.accept(record);
112 Integer partition = record.partition();
113 String key = record.key() == null ? "NULL" : record.key();
114 Map<String, Long> byKey = seen.get(partition);
116 if (!byKey.containsKey(key))
119 long seenByKey = byKey.get(key);
121 byKey.put(key, seenByKey);
125 catch(WakeupException e)
127 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
128 consumer.commitSync();
133 log.error("{} - Unexpected error: {}", id, e.toString(), e);
138 log.info("{} - Consumer-Thread exiting", id);
142 private void shutdown()
147 private void shutdown(Exception e)
154 log.info("{} - Unsubscribing from topic {}", id, topic);
155 consumer.unsubscribe();
160 "{} - Error while unsubscribing from topic {}: {}",
178 public Map<Integer, Map<String, Long>> getSeen()
189 throw new IllegalStateException("Consumer instance " + id + " is already running!");
191 log.info("{} - Starting - consumed {} messages before", id, consumed);
194 executor.submit(this);
202 public synchronized void stop() throws ExecutionException, InterruptedException
208 throw new IllegalStateException("Consumer instance " + id + " is not running!");
210 log.info("{} - Stopping", id);
213 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
222 public void destroy() throws ExecutionException, InterruptedException
224 log.info("{} - Destroy!", id);
229 catch (IllegalStateException e)
231 log.info("{} - Was already stopped", id);
235 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
239 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
243 public boolean running()
256 public Optional<Exception> exitStatus()
262 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
264 return Optional.ofNullable(exception);