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 RecordHandler<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;
38 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
40 partitions.forEach(tp -> handler.onPartitionRevoked(tp));
44 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
46 partitions.forEach(tp -> handler.onPartitionAssigned(tp));
55 log.info("{} - Subscribing to topic {}", id, topic);
56 consumer.subscribe(Arrays.asList(topic), this);
60 ConsumerRecords<K, V> records =
61 consumer.poll(Duration.ofSeconds(1));
63 // Do something with the data...
64 log.info("{} - Received {} messages", id, records.count());
65 for (ConsumerRecord<K, V> record : records)
68 "{} - {}: {}/{} - {}={}",
77 handler.accept(record);
82 handler.beforeNextPoll();
85 catch(WakeupException e)
87 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
90 catch(RecordDeserializationException e)
92 TopicPartition tp = e.topicPartition();
93 long offset = e.offset();
95 "{} - Could not deserialize message on topic {} with offset={}: {}",
99 e.getCause().toString());
105 log.error("{} - Unexpected error: {}", id, e.toString(), e);
110 log.info("{} - Consumer-Thread exiting", id);
114 private void shutdown()
119 private void shutdown(Exception e)
126 log.info("{} - Unsubscribing from topic {}", id, topic);
127 consumer.unsubscribe();
132 "{} - Error while unsubscribing from topic {}: {}",
156 throw new IllegalStateException("Consumer instance " + id + " is already running!");
158 log.info("{} - Starting - consumed {} messages before", id, consumed);
161 executor.submit(this);
169 public synchronized void stop() throws InterruptedException
175 throw new IllegalStateException("Consumer instance " + id + " is not running!");
177 log.info("{} - Stopping", id);
180 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
189 public void destroy() throws ExecutionException, InterruptedException
191 log.info("{} - Destroy!", id);
192 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
195 public boolean running()
208 public Optional<Exception> exitStatus()
214 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
216 return Optional.ofNullable(exception);