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;
28 private final Lock lock = new ReentrantLock();
29 private final Condition condition = lock.newCondition();
30 private boolean running = false;
31 private Exception exception;
32 private long consumed = 0;
34 private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
35 private final Map<Integer, Long> offsets = new HashMap<>();
43 log.info("{} - Subscribing to topic {}", id, topic);
44 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
47 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
49 partitions.forEach(tp ->
51 Integer partition = tp.partition();
52 Long newOffset = consumer.position(tp);
53 Long oldOffset = offsets.remove(partition);
55 "{} - removing partition: {}, consumed {} records (offset {} -> {})",
58 newOffset - oldOffset,
61 Map<String, Long> removed = seen.remove(partition);
62 for (String key : removed.keySet())
65 "{} - Seen {} messages for partition={}|key={}",
75 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
77 partitions.forEach(tp ->
79 Integer partition = tp.partition();
80 Long offset = consumer.position(tp);
81 log.info("{} - adding partition: {}, offset={}", id, partition, offset);
82 offsets.put(partition, offset);
83 seen.put(partition, new HashMap<>());
90 ConsumerRecords<String, String> records =
91 consumer.poll(Duration.ofSeconds(1));
93 // Do something with the data...
94 log.info("{} - Received {} messages", id, records.count());
95 for (ConsumerRecord<String, String> record : records)
99 "{} - {}: {}/{} - {}={}",
108 Integer partition = record.partition();
109 String key = record.key() == null ? "NULL" : record.key();
110 Map<String, Long> byKey = seen.get(partition);
112 if (!byKey.containsKey(key))
115 long seenByKey = byKey.get(key);
117 byKey.put(key, seenByKey);
121 catch(WakeupException e)
123 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
124 consumer.commitSync();
129 log.error("{} - Unexpected error: {}", id, e.toString(), e);
134 log.info("{} - Consumer-Thread exiting", id);
138 private void shutdown()
143 private void shutdown(Exception e)
150 log.info("{} - Unsubscribing from topic {}", id, topic);
151 consumer.unsubscribe();
156 "{} - Error while unsubscribing from topic {}: {}",
174 public Map<Integer, Map<String, Long>> getSeen()
185 throw new IllegalStateException("Consumer instance " + id + " is already running!");
187 log.info("{} - Starting - consumed {} messages before", id, consumed);
190 executor.submit(this);
198 public synchronized void stop() throws ExecutionException, InterruptedException
204 throw new IllegalStateException("Consumer instance " + id + " is not running!");
206 log.info("{} - Stopping", id);
209 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
218 public void destroy() throws ExecutionException, InterruptedException
220 log.info("{} - Destroy!", id);
225 catch (IllegalStateException e)
227 log.info("{} - Was already stopped", id);
231 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
235 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
239 public boolean running()
252 public Optional<Exception> exitStatus()
258 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
260 return Optional.ofNullable(exception);