`CompletableFuture.whenComplete(...)` ist deutlich näher an dem Callback spring/spring-producer--kafkatemplate--COMMITS--2025-02
authorKai Moritz <kai@juplo.de>
Tue, 11 Feb 2025 10:12:58 +0000 (11:12 +0100)
committerKai Moritz <kai@juplo.de>
Fri, 14 Feb 2025 13:16:11 +0000 (14:16 +0100)
src/main/java/de/juplo/kafka/ExampleProducer.java

index 864eed2..143472d 100644 (file)
@@ -82,12 +82,12 @@ public class ExampleProducer implements Runnable
   {
     final long time = System.currentTimeMillis();
 
-    CompletableFuture<SendResult<String, String>> completableFuture = kafkaTemplate.send(topic, key, value);
-
-    completableFuture.thenAccept(result ->
+    kafkaTemplate.send(topic, key, value).whenComplete((result, e) ->
+    {
+      long now = System.currentTimeMillis();
+      if (e == null)
       {
         // HANDLE SUCCESS
-        long now = System.currentTimeMillis();
         RecordMetadata metadata = result.getRecordMetadata();
         produced++;
         log.debug(
@@ -100,12 +100,10 @@ public class ExampleProducer implements Runnable
             metadata.timestamp(),
             now - time
         );
-      });
-
-    completableFuture.exceptionally(e ->
+      }
+      else
       {
         // HANDLE ERROR
-        long now = System.currentTimeMillis();
         log.error(
             "{} - ERROR for message {}={}, latency={}ms: {}",
             id,
@@ -114,8 +112,8 @@ public class ExampleProducer implements Runnable
             now - time,
             e.toString()
         );
-        return null;
-      });
+      }
+    });
 
     long now = System.currentTimeMillis();
     log.trace(