From 84fed0ec1d13f26d636abcb38c201c9d13dbc46c Mon Sep 17 00:00:00 2001 From: Kai Moritz Date: Sun, 10 Apr 2022 21:56:37 +0200 Subject: [PATCH] HealthIndicator implementiert --- .../java/de/juplo/kafka/EndlessConsumer.java | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/juplo/kafka/EndlessConsumer.java b/src/main/java/de/juplo/kafka/EndlessConsumer.java index 18cef23..adebff1 100644 --- a/src/main/java/de/juplo/kafka/EndlessConsumer.java +++ b/src/main/java/de/juplo/kafka/EndlessConsumer.java @@ -10,6 +10,7 @@ import org.apache.kafka.common.serialization.StringDeserializer; import javax.annotation.PreDestroy; import java.time.Duration; import java.util.Arrays; +import java.util.Optional; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -31,6 +32,7 @@ public class EndlessConsumer implements Runnable private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private boolean running = false; + private Exception exception; private long consumed = 0; private KafkaConsumer consumer = null; @@ -99,7 +101,7 @@ public class EndlessConsumer implements Runnable catch(Exception e) { log.error("{} - Unexpected error: {}", id, e.toString(), e); - shutdown(); + shutdown(e); } finally { @@ -110,11 +112,17 @@ public class EndlessConsumer implements Runnable } private void shutdown() + { + shutdown(null); + } + + private void shutdown(Exception e) { lock.lock(); try { running = false; + exception = e; condition.signal(); } finally @@ -133,6 +141,7 @@ public class EndlessConsumer implements Runnable log.info("{} - Starting - consumed {} messages before", id, consumed); running = true; + exception = null; executor.submit(this); } finally @@ -181,4 +190,33 @@ public class EndlessConsumer implements Runnable log.info("{}: Consumed {} messages in total, exiting!", id, consumed); } } + + public boolean running() + { + lock.lock(); + try + { + return running; + } + finally + { + lock.unlock(); + } + } + + public Optional exitStatus() + { + lock.lock(); + try + { + if (running) + throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!"); + + return Optional.ofNullable(exception); + } + finally + { + lock.unlock(); + } + } } -- 2.20.1