Auf `@KafkaHandler` umgestellt
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
index e4d9697..d3d11ae 100644 (file)
@@ -1,68 +1,39 @@
 package de.juplo.kafka;
 
+import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
-import org.apache.kafka.clients.consumer.ConsumerRecords;
-import org.apache.kafka.clients.consumer.KafkaConsumer;
-import org.apache.kafka.common.errors.WakeupException;
-import org.apache.kafka.common.serialization.StringDeserializer;
+import org.springframework.kafka.annotation.KafkaListener;
+import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
 
-import java.time.Duration;
-import java.util.Arrays;
-import java.util.Properties;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
+import java.util.List;
+import java.util.Optional;
 
 
+@RequiredArgsConstructor
 @Slf4j
-public class SimpleConsumer
+public class EndlessConsumer<K, V>
 {
-  private long consumed = 0;
-  private KafkaConsumer<String, String> consumer;
-  private Lock lock = new ReentrantLock();
-  private Condition stopped = lock.newCondition();
-
+  private final String id;
+  private final KafkaListenerEndpointRegistry registry;
+  private final ApplicationErrorHandler errorHandler;
+  private final RecordHandler<K, V> recordHandler;
 
-  public SimpleConsumer()
-  {
-    // tag::create[]
-    Properties props = new Properties();
-    props.put("bootstrap.servers", ":9092");
-    props.put("group.id", "my-consumer"); // << Used for Offset-Commits
-    // end::create[]
-    props.put("auto.offset.reset", "earliest");
-    // tag::create[]
-    props.put("key.deserializer", StringDeserializer.class.getName());
-    props.put("value.deserializer", StringDeserializer.class.getName());
-
-    KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
-    // end::create[]
-    this.consumer = consumer;
-  }
+  private long consumed = 0;
 
 
-  public void run()
+  @KafkaListener(
+      id = "${spring.kafka.client-id}",
+      idIsGroup = false,
+      topics = "${sumup.adder.topic}",
+      batch = "true",
+      autoStartup = "false")
+  public void accept(List<ConsumerRecord<K, V>> records)
   {
-    String id = "C";
-
-    try
-    {
-      log.info("{} - Subscribing to topic test", id);
-      consumer.subscribe(Arrays.asList("test"));
-
-      // tag::loop[]
-      while (true)
-      {
-        ConsumerRecords<String, String> records =
-            consumer.poll(Duration.ofSeconds(1));
-
         // Do something with the data...
-        // end::loop[]
-        log.info("{} - Received {} messages", id, records.count());
-        for (ConsumerRecord<String, String> record : records)
+        log.info("{} - Received {} messages", id, records.size());
+        for (ConsumerRecord<K, V> record : records)
         {
-          consumed++;
           log.info(
               "{} - {}: {}/{} - {}={}",
               id,
@@ -72,60 +43,43 @@ public class SimpleConsumer
               record.key(),
               record.value()
           );
+
+          recordHandler.accept(record);
+
+          consumed++;
         }
-        // tag::loop[]
-      }
-      // end::loop[]
-    }
-    catch(WakeupException e)
-    {
-      log.info("{} - RIIING!", id);
-    }
-    catch(Exception e)
-    {
-      log.error("{} - Unexpected error: {}", id, e.toString());
-    }
-    finally
-    {
-      this.lock.lock();
-      try
-      {
-        log.info("{} - Closing the KafkaConsumer", id);
-        consumer.close();
-        log.info("C - DONE!");
-        stopped.signal();
-      }
-      finally
-      {
-        this.lock.unlock();
-        log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
-      }
-    }
   }
 
+  public void start()
+  {
+    if (running())
+      throw new IllegalStateException("Consumer instance " + id + " is already running!");
+
+    log.info("{} - Starting - consumed {} messages before", id, consumed);
+    errorHandler.clearState();
+    registry.getListenerContainer(id).start();
+  }
 
-  public static void main(String[] args) throws Exception
+  public void stop()
   {
-    SimpleConsumer instance = new SimpleConsumer();
-
-    Runtime.getRuntime().addShutdownHook(new Thread(() ->
-    {
-      instance.lock.lock();
-      try
-      {
-        instance.consumer.wakeup();
-        instance.stopped.await();
-      }
-      catch (InterruptedException e)
-      {
-        log.warn("Interrrupted while waiting for the consumer to stop!", e);
-      }
-      finally
-      {
-        instance.lock.unlock();
-      }
-    }));
-
-    instance.run();
+    if (!running())
+      throw new IllegalStateException("Consumer instance " + id + " is not running!");
+
+    log.info("{} - Stopping", id);
+    registry.getListenerContainer(id).stop();
+    log.info("{} - Stopped - consumed {} messages so far", id, consumed);
+  }
+
+  public boolean running()
+  {
+    return registry.getListenerContainer(id).isRunning();
+  }
+
+  public Optional<Exception> exitStatus()
+  {
+    if (running())
+      throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
+
+    return errorHandler.getException();
   }
 }