Refaktorisierungen aus 'wordcount' nach 'stored-offsets' zurück portiert
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
index ce5dd72..58557f2 100644 (file)
@@ -8,9 +8,7 @@ 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;
@@ -21,16 +19,14 @@ import java.util.concurrent.locks.ReentrantLock;
 
 @Slf4j
 @RequiredArgsConstructor
-public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnable
+public class EndlessConsumer<K, V> implements Runnable
 {
   private final ExecutorService executor;
-  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;
+  private final PollIntervalAwareConsumerRebalanceListener pollIntervalAwareRebalanceListener;
+  private final RecordHandler<K, V> handler;
 
   private final Lock lock = new ReentrantLock();
   private final Condition condition = lock.newCondition();
@@ -38,56 +34,6 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
   private Exception exception;
   private long consumed = 0;
 
-  private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
-
-
-  @Override
-  public void onPartitionsRevoked(Collection<TopicPartition> partitions)
-  {
-    partitions.forEach(tp ->
-    {
-      Integer partition = tp.partition();
-      Long newOffset = consumer.position(tp);
-      log.info(
-          "{} - removing partition: {}, offset of next message {})",
-          id,
-          partition,
-          newOffset);
-      Map<String, Long> removed = seen.remove(partition);
-      for (String key : removed.keySet())
-      {
-        log.info(
-            "{} - Seen {} messages for partition={}|key={}",
-            id,
-            removed.get(key),
-            partition,
-            key);
-      }
-      repository.save(new StatisticsDocument(partition, removed, consumer.position(tp)));
-    });
-  }
-
-  @Override
-  public void onPartitionsAssigned(Collection<TopicPartition> partitions)
-  {
-    partitions.forEach(tp ->
-    {
-      Integer partition = tp.partition();
-      Long offset = consumer.position(tp);
-      log.info("{} - adding partition: {}, offset={}", id, partition, offset);
-      StatisticsDocument document =
-          repository
-              .findById(Integer.toString(partition))
-              .orElse(new StatisticsDocument(partition));
-      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);
-    });
-  }
 
 
   @Override
@@ -96,9 +42,7 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
     try
     {
       log.info("{} - Subscribing to topic {}", id, topic);
-      consumer.subscribe(Arrays.asList(topic), this);
-
-      Instant lastCommit = clock.instant();
+      consumer.subscribe(Arrays.asList(topic), pollIntervalAwareRebalanceListener);
 
       while (true)
       {
@@ -122,29 +66,9 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
           handler.accept(record);
 
           consumed++;
-
-          Integer partition = record.partition();
-          String key = record.key() == null ? "NULL" : record.key().toString();
-          Map<String, Long> byKey = seen.get(partition);
-
-          if (!byKey.containsKey(key))
-            byKey.put(key, 0l);
-
-          long seenByKey = byKey.get(key);
-          seenByKey++;
-          byKey.put(key, seenByKey);
         }
 
-        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();
-        }
+        pollIntervalAwareRebalanceListener.beforeNextPoll();
       }
     }
     catch(WakeupException e)
@@ -212,11 +136,6 @@ public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnabl
     }
   }
 
-  public Map<Integer, Map<String, Long>> getSeen()
-  {
-    return seen;
-  }
-
   public void start()
   {
     lock.lock();
@@ -236,7 +155,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