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;
9 import org.springframework.context.ConfigurableApplicationContext;
11 import java.time.Duration;
13 import java.util.concurrent.ExecutorService;
17 @RequiredArgsConstructor
18 public class EndlessConsumer<K, V> implements Runnable
20 private final ExecutorService executor;
21 private final ConfigurableApplicationContext applicationContext;
22 private final String id;
23 private final String topic;
24 private final Consumer<K, V> consumer;
25 private final ConsumerRebalanceListener rebalanceListener;
26 private final RecordHandler<K, V> recordHandler;
28 private boolean running = false;
29 private Exception exception = null;
30 private long consumed = 0;
39 log.info("{} - Subscribing to topic {}", id, topic);
40 consumer.subscribe(Arrays.asList(topic), rebalanceListener);
44 ConsumerRecords<K, V> records =
45 consumer.poll(Duration.ofSeconds(1));
47 // Do something with the data...
48 log.info("{} - Received {} messages", id, records.count());
49 for (ConsumerRecord<K, V> record : records)
52 "{} - {}: {}/{} - {}={}",
61 recordHandler.accept(record);
67 catch(WakeupException e)
69 log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
71 catch(RecordDeserializationException e)
73 TopicPartition tp = e.topicPartition();
74 long offset = e.offset();
76 "{} - Could not deserialize message on topic {} with offset={}: {}",
80 e.getCause().toString());
85 log.error("{} - Unexpected error: {}", id, e.toString(), e);
87 log.info("{} - Unsubscribing...", id);
88 consumer.unsubscribe();
93 log.info("{} - Closing the consumer...", id);
95 log.info("{} - Shutting down the app...", id);
96 applicationContext.close();
97 log.info("{} - Consumer-Thread exiting", id);
104 throw new IllegalStateException("Consumer instance " + id + " is already running!");
106 log.info("{} - Starting - consumed {} messages before", id, consumed);
108 executor.submit(this);
115 public boolean running()
120 public Optional<Exception> exitStatus()
123 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
125 return Optional.ofNullable(exception);