Endless Consumer: a simple consumer, implemented as Spring-Boot-App
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
index e4d9697..22dce95 100644 (file)
@@ -7,58 +7,68 @@ import org.apache.kafka.clients.consumer.KafkaConsumer;
 import org.apache.kafka.common.errors.WakeupException;
 import org.apache.kafka.common.serialization.StringDeserializer;
 
+import javax.annotation.PreDestroy;
 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.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 
 @Slf4j
-public class SimpleConsumer
+public class EndlessConsumer implements Runnable
 {
-  private long consumed = 0;
-  private KafkaConsumer<String, String> consumer;
-  private Lock lock = new ReentrantLock();
-  private Condition stopped = lock.newCondition();
+  private final ExecutorService executor;
+  private final String bootstrapServer;
+  private final String groupId;
+  private final String id;
+  private final String topic;
 
+  private AtomicBoolean running = new AtomicBoolean();
+  private long consumed = 0;
+  private KafkaConsumer<String, String> consumer = null;
+  private Future<?> future = null;
+
+  public EndlessConsumer(
+      ExecutorService executor,
+      String bootstrapServer,
+      String groupId,
+      String clientId,
+      String topic)
+  {
+    this.executor = executor;
+    this.bootstrapServer = bootstrapServer;
+    this.groupId = groupId;
+    this.id = clientId;
+    this.topic = topic;
+  }
 
-  public SimpleConsumer()
+  @Override
+  public void run()
   {
-    // 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("bootstrap.servers", bootstrapServer);
+    props.put("group.id", groupId);
+    props.put("client.id", id);
     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;
-  }
-
-
-  public void run()
-  {
-    String id = "C";
+    this.consumer = new KafkaConsumer<>(props);
 
     try
     {
-      log.info("{} - Subscribing to topic test", id);
-      consumer.subscribe(Arrays.asList("test"));
+      log.info("{} - Subscribing to topic {}", id, topic);
+      consumer.subscribe(Arrays.asList(topic));
 
-      // 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)
         {
@@ -73,9 +83,7 @@ public class SimpleConsumer
               record.value()
           );
         }
-        // tag::loop[]
       }
-      // end::loop[]
     }
     catch(WakeupException e)
     {
@@ -84,48 +92,54 @@ public class SimpleConsumer
     catch(Exception e)
     {
       log.error("{} - Unexpected error: {}", id, e.toString());
+      running.set(false); // Mark the instance as not running
     }
     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);
-      }
+      log.info("{} - Closing the KafkaConsumer", id);
+      consumer.close();
+      log.info("{} - Consumer-Thread exiting", id);
     }
   }
 
 
-  public static void main(String[] args) throws Exception
+  public synchronized void start()
   {
-    SimpleConsumer instance = new SimpleConsumer();
+    boolean stateChanged = running.compareAndSet(false, true);
+    if (!stateChanged)
+      throw new RuntimeException("Consumer instance " + id + " is already running!");
 
-    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();
-      }
-    }));
+    log.info("{} - Starting - consumed {} messages before", id, consumed);
+    future = executor.submit(this);
+  }
 
-    instance.run();
+  public synchronized void stop() throws ExecutionException, InterruptedException
+  {
+    boolean stateChanged = running.compareAndSet(true, false);
+    if (!stateChanged)
+      throw new RuntimeException("Consumer instance " + id + " is not running!");
+
+    log.info("{} - Stopping", id);
+    consumer.wakeup();
+    future.get();
+    log.info("{} - Stopped - consumed {} messages so far", id, consumed);
+  }
+
+  @PreDestroy
+  public void destroy() throws ExecutionException, InterruptedException
+  {
+    log.info("{} - Destroy!", id);
+    try
+    {
+      stop();
+    }
+    catch (IllegalStateException e)
+    {
+      log.info("{} - Was already stopped", id);
+    }
+    finally
+    {
+      log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
+    }
   }
 }