Verschachtelte Map gegen fachliche Datenstruktur ausgetauscht
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
index be371ae..e3a60b5 100644 (file)
@@ -33,7 +33,7 @@ public class EndlessConsumer implements Runnable
   private KafkaConsumer<String, String> consumer = null;
   private Future<?> future = null;
 
-  private final Map<Integer, Map<String, Integer>> seen = new HashMap<>();
+  private final Map<TopicPartition, PartitionStatistics> seen = new HashMap<>();
 
 
   public EndlessConsumer(
@@ -77,15 +77,15 @@ public class EndlessConsumer implements Runnable
           partitions.forEach(tp ->
           {
             log.info("{} - removing partition: {}", id, tp);
-            Map<String, Integer> removed = seen.remove(tp.partition());
-            for (String key : removed.keySet())
+            PartitionStatistics removed = seen.remove(tp);
+            for (KeyCounter counter : removed.getStatistics())
             {
               log.info(
                   "{} - Seen {} messages for partition={}|key={}",
                   id,
-                  removed.get(key),
-                  removed,
-                  key);
+                  counter.getCounter(),
+                  removed.getPartition(),
+                  counter.getKey());
             }
           });
         }
@@ -96,7 +96,7 @@ public class EndlessConsumer implements Runnable
           partitions.forEach(tp ->
           {
             log.info("{} - adding partition: {}", id, tp);
-            seen.put(tp.partition(), new HashMap<>());
+            seen.put(tp, new PartitionStatistics(tp));
           });
         }
       });
@@ -121,16 +121,9 @@ public class EndlessConsumer implements Runnable
               record.value()
           );
 
-          Integer partition = record.partition();
+          TopicPartition partition = new TopicPartition(record.topic(), record.partition());
           String key = record.key() == null ? "NULL" : record.key();
-          Map<String, Integer> byKey = seen.get(partition);
-
-          if (!byKey.containsKey(key))
-            byKey.put(key, 0);
-
-          int seenByKey = byKey.get(key);
-          seenByKey++;
-          byKey.put(key, seenByKey);
+          seen.get(partition).increment(key);
         }
       }
     }
@@ -151,7 +144,7 @@ public class EndlessConsumer implements Runnable
     }
   }
 
-  public Map<Integer, Map<String, Integer>> getSeen()
+  public Map<TopicPartition, PartitionStatistics> getSeen()
   {
     return seen;
   }