1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
6 import org.apache.kafka.clients.consumer.ConsumerRecords;
7 import org.apache.kafka.clients.consumer.KafkaConsumer;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.WakeupException;
10 import org.apache.kafka.common.serialization.StringDeserializer;
12 import javax.annotation.PreDestroy;
13 import java.time.Duration;
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 public class EndlessConsumer implements Runnable
25 private final ExecutorService executor;
26 private final String bootstrapServer;
27 private final String groupId;
28 private final String id;
29 private final String topic;
30 private final String autoOffsetReset;
32 private final Lock lock = new ReentrantLock();
33 private final Condition condition = lock.newCondition();
34 private boolean running = false;
35 private Exception exception;
36 private long consumed = 0;
37 private KafkaConsumer<String, String> consumer = null;
40 private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
41 private final Map<Integer, Long> offsets = new HashMap<>();
44 public EndlessConsumer(
45 ExecutorService executor,
46 String bootstrapServer,
50 String autoOffsetReset)
52 this.executor = executor;
53 this.bootstrapServer = bootstrapServer;
54 this.groupId = groupId;
57 this.autoOffsetReset = autoOffsetReset;
65 Properties props = new Properties();
66 props.put("bootstrap.servers", bootstrapServer);
67 props.put("group.id", groupId);
68 props.put("client.id", id);
69 props.put("auto.offset.reset", autoOffsetReset);
70 props.put("metadata.max.age.ms", "1000");
71 props.put("key.deserializer", StringDeserializer.class.getName());
72 props.put("value.deserializer", StringDeserializer.class.getName());
74 this.consumer = new KafkaConsumer<>(props);
76 log.info("{} - Subscribing to topic {}", id, topic);
77 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
80 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
82 partitions.forEach(tp ->
84 Integer partition = tp.partition();
85 Long newOffset = consumer.position(tp);
86 Long oldOffset = offsets.remove(partition);
88 "{} - removing partition: {}, consumed {} records (offset {} -> {})",
91 newOffset - oldOffset,
94 Map<String, Long> removed = seen.remove(partition);
95 for (String key : removed.keySet())
98 "{} - Seen {} messages for partition={}|key={}",
108 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
110 partitions.forEach(tp ->
112 Integer partition = tp.partition();
113 Long offset = consumer.position(tp);
114 log.info("{} - adding partition: {}, offset={}", id, partition, offset);
115 offsets.put(partition, offset);
116 seen.put(partition, new HashMap<>());
123 ConsumerRecords<String, String> records =
124 consumer.poll(Duration.ofSeconds(1));
126 // Do something with the data...
127 log.info("{} - Received {} messages", id, records.count());
128 for (ConsumerRecord<String, String> record : records)
132 "{} - {}: {}/{} - {}={}",
141 Integer partition = record.partition();
142 String key = record.key() == null ? "NULL" : record.key();
143 Map<String, Long> byKey = seen.get(partition);
145 if (!byKey.containsKey(key))
148 long seenByKey = byKey.get(key);
150 byKey.put(key, seenByKey);
154 catch(WakeupException e)
156 log.info("{} - RIIING!", id);
161 log.error("{} - Unexpected error: {}", id, e.toString(), e);
166 log.info("{} - Closing the KafkaConsumer", id);
168 log.info("{} - Consumer-Thread exiting", id);
172 private void shutdown()
177 private void shutdown(Exception e)
192 public Map<Integer, Map<String, Long>> getSeen()
203 throw new IllegalStateException("Consumer instance " + id + " is already running!");
205 log.info("{} - Starting - consumed {} messages before", id, consumed);
208 executor.submit(this);
216 public synchronized void stop() throws ExecutionException, InterruptedException
222 throw new IllegalStateException("Consumer instance " + id + " is not running!");
224 log.info("{} - Stopping", id);
227 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
236 public void destroy() throws ExecutionException, InterruptedException
238 log.info("{} - Destroy!", id);
243 catch (IllegalStateException e)
245 log.info("{} - Was already stopped", id);
249 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
253 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
257 public boolean running()
270 public Optional<Exception> exitStatus()
276 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
278 return Optional.ofNullable(exception);