`ExampleConsumer` über Generics typisiert
authorKai Moritz <kai@juplo.de>
Thu, 20 Feb 2025 17:36:13 +0000 (18:36 +0100)
committerKai Moritz <kai@juplo.de>
Sat, 15 Mar 2025 18:22:13 +0000 (19:22 +0100)
src/main/java/de/juplo/kafka/ApplicationConfiguration.java
src/main/java/de/juplo/kafka/ExampleConsumer.java

index b98c401..d2b8e05 100644 (file)
@@ -17,13 +17,13 @@ import java.util.Properties;
 public class ApplicationConfiguration
 {
   @Bean
-  public ExampleConsumer exampleConsumer(
+  public ExampleConsumer<String, String> exampleConsumer(
     Consumer<String, String> kafkaConsumer,
     ApplicationProperties properties,
     ConfigurableApplicationContext applicationContext)
   {
     return
-      new ExampleConsumer(
+      new ExampleConsumer<>(
         properties.getClientId(),
         properties.getConsumerProperties().getTopic(),
         kafkaConsumer,
index 1f5a570..101abd1 100644 (file)
@@ -11,11 +11,11 @@ import java.util.Arrays;
 
 
 @Slf4j
-public class ExampleConsumer implements Runnable
+public class ExampleConsumer<K, V> implements Runnable
 {
   private final String id;
   private final String topic;
-  private final Consumer<String, String> consumer;
+  private final Consumer<K, V> consumer;
   private final Thread workerThread;
   private final Runnable closeCallback;
 
@@ -25,7 +25,7 @@ public class ExampleConsumer implements Runnable
   public ExampleConsumer(
     String clientId,
     String topic,
-    Consumer<String, String> consumer,
+    Consumer<K, V> consumer,
     Runnable closeCallback)
   {
     this.id = clientId;
@@ -49,10 +49,10 @@ public class ExampleConsumer implements Runnable
 
       while (true)
       {
-        ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
+        ConsumerRecords<K, V> records = consumer.poll(Duration.ofSeconds(1));
 
         log.info("{} - Received {} messages", id, records.count());
-        for (ConsumerRecord<String, String> record : records)
+        for (ConsumerRecord<K, V> record : records)
         {
           handleRecord(
             record.topic(),
@@ -86,8 +86,8 @@ public class ExampleConsumer implements Runnable
     String topic,
     Integer partition,
     Long offset,
-    String key,
-    String value)
+    K key,
+    V value)
   {
     consumed++;
     log.info("{} - partition={}-{}, offset={}: {}={}", id, topic, partition, offset, key, value);