Tests: Umbau für einen Commit im Fehlerfall und Anpassung des Tests
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
index 38dd360..b173b12 100644 (file)
@@ -4,6 +4,7 @@ import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.kafka.clients.consumer.*;
 import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.RecordDeserializationException;
 import org.apache.kafka.common.errors.WakeupException;
 
 import javax.annotation.PreDestroy;
@@ -18,13 +19,13 @@ import java.util.concurrent.locks.ReentrantLock;
 
 @Slf4j
 @RequiredArgsConstructor
-public class EndlessConsumer implements Runnable
+public class EndlessConsumer<K, V> implements Runnable
 {
   private final ExecutorService executor;
   private final String id;
   private final String topic;
-  private final Consumer<String, String> consumer;
-  private final java.util.function.Consumer<ConsumerRecord<String, String>> handler;
+  private final Consumer<K, V> consumer;
+  private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
 
   private final Lock lock = new ReentrantLock();
   private final Condition condition = lock.newCondition();
@@ -88,12 +89,12 @@ public class EndlessConsumer implements Runnable
 
       while (true)
       {
-        ConsumerRecords<String, String> records =
+        ConsumerRecords<K, V> records =
             consumer.poll(Duration.ofSeconds(1));
 
         // Do something with the data...
         log.info("{} - Received {} messages", id, records.count());
-        for (ConsumerRecord<String, String> record : records)
+        for (ConsumerRecord<K, V> record : records)
         {
           log.info(
               "{} - {}: {}/{} - {}={}",
@@ -110,7 +111,7 @@ public class EndlessConsumer implements Runnable
           consumed++;
 
           Integer partition = record.partition();
-          String key = record.key() == null ? "NULL" : record.key();
+          String key = record.key() == null ? "NULL" : record.key().toString();
           Map<String, Long> byKey = seen.get(partition);
 
           if (!byKey.containsKey(key))
@@ -128,6 +129,20 @@ public class EndlessConsumer implements Runnable
       consumer.commitSync();
       shutdown();
     }
+    catch(RecordDeserializationException e)
+    {
+      TopicPartition tp = e.topicPartition();
+      long offset = e.offset();
+      log.error(
+          "{} - Could not deserialize  message on topic {} with offset={}: {}",
+          id,
+          tp,
+          offset,
+          e.getCause().toString());
+
+      consumer.commitSync();
+      shutdown(e);
+    }
     catch(Exception e)
     {
       log.error("{} - Unexpected error: {}", id, e.toString(), e);