Umstellung des Nachrichten-Datentyps auf Long zurückgenommen
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
index 2a3445c..f9a9629 100644 (file)
@@ -8,7 +8,9 @@ import org.apache.kafka.common.errors.RecordDeserializationException;
 import org.apache.kafka.common.errors.WakeupException;
 
 import javax.annotation.PreDestroy;
+import java.time.Clock;
 import java.time.Duration;
+import java.time.Instant;
 import java.util.*;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
@@ -25,6 +27,8 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
   private final PartitionStatisticsRepository repository;
   private final String id;
   private final String topic;
+  private final Clock clock;
+  private final Duration commitInterval;
   private final Consumer<K, V> consumer;
   private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
 
@@ -35,7 +39,6 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
   private long consumed = 0;
 
   private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
-  private final Map<Integer, Long> offsets = new HashMap<>();
 
 
   @Override
@@ -45,13 +48,10 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
     {
       Integer partition = tp.partition();
       Long newOffset = consumer.position(tp);
-      Long oldOffset = offsets.remove(partition);
       log.info(
-          "{} - removing partition: {}, consumed {} records (offset {} -> {})",
+          "{} - removing partition: {}, offset of next message {})",
           id,
           partition,
-          newOffset - oldOffset,
-          oldOffset,
           newOffset);
       Map<String, Long> removed = seen.remove(partition);
       for (String key : removed.keySet())
@@ -79,7 +79,12 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
           repository
               .findById(Integer.toString(partition))
               .orElse(new StatisticsDocument(partition));
-      consumer.seek(tp, document.offset);
+      if (document.offset >= 0)
+      {
+        // Only seek, if a stored offset was found
+        // Otherwise: Use initial offset, generated by Kafka
+        consumer.seek(tp, document.offset);
+      }
       seen.put(partition, document.statistics);
     });
   }
@@ -93,6 +98,8 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
       log.info("{} - Subscribing to topic {}", id, topic);
       consumer.subscribe(Arrays.asList(topic), this);
 
+      Instant lastCommit = clock.instant();
+
       while (true)
       {
         ConsumerRecords<K, V> records =
@@ -128,11 +135,16 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
           byKey.put(key, seenByKey);
         }
 
-        seen.forEach((partiton, statistics) -> repository.save(
-            new StatisticsDocument(
-                partiton,
-                statistics,
-                consumer.position(new TopicPartition(topic, partiton)))));
+        if (lastCommit.plus(commitInterval).isBefore(clock.instant()))
+        {
+          log.debug("Storing data and offsets, last commit: {}", lastCommit);
+          seen.forEach((partiton, statistics) -> repository.save(
+              new StatisticsDocument(
+                  partiton,
+                  statistics,
+                  consumer.position(new TopicPartition(topic, partiton)))));
+          lastCommit = clock.instant();
+        }
       }
     }
     catch(WakeupException e)
@@ -224,7 +236,7 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
     }
   }
 
-  public synchronized void stop() throws ExecutionException, InterruptedException
+  public synchronized void stop() throws InterruptedException
   {
     lock.lock();
     try
@@ -247,22 +259,7 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
   public void destroy() throws ExecutionException, InterruptedException
   {
     log.info("{} - Destroy!", id);
-    try
-    {
-      stop();
-    }
-    catch (IllegalStateException e)
-    {
-      log.info("{} - Was already stopped", id);
-    }
-    catch (Exception e)
-    {
-      log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
-    }
-    finally
-    {
-      log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
-    }
+    log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
   }
 
   public boolean running()