1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.apache.kafka.clients.consumer.ConsumerRecords;
6 import org.apache.kafka.clients.consumer.KafkaConsumer;
7 import org.apache.kafka.common.errors.WakeupException;
8 import org.apache.kafka.common.serialization.StringDeserializer;
10 import javax.annotation.PreDestroy;
11 import java.time.Duration;
12 import java.util.Arrays;
13 import java.util.HashMap;
15 import java.util.Optional;
16 import java.util.Properties;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.ExecutorService;
19 import java.util.concurrent.locks.Condition;
20 import java.util.concurrent.locks.Lock;
21 import java.util.concurrent.locks.ReentrantLock;
25 public class EndlessConsumer implements Runnable
27 private final ExecutorService executor;
28 private final String bootstrapServer;
29 private final String groupId;
30 private final String id;
31 private final String topic;
32 private final String autoOffsetReset;
34 private final Lock lock = new ReentrantLock();
35 private final Condition condition = lock.newCondition();
36 private boolean running = false;
37 private Exception exception;
38 private long consumed = 0;
39 private KafkaConsumer<String, String> consumer = null;
42 private Map<Integer, Map<String, Integer>> seen;
45 public EndlessConsumer(
46 ExecutorService executor,
47 String bootstrapServer,
51 String autoOffsetReset)
53 this.executor = executor;
54 this.bootstrapServer = bootstrapServer;
55 this.groupId = groupId;
58 this.autoOffsetReset = autoOffsetReset;
66 Properties props = new Properties();
67 props.put("bootstrap.servers", bootstrapServer);
68 props.put("group.id", groupId);
69 props.put("client.id", id);
70 props.put("auto.offset.reset", autoOffsetReset);
71 props.put("metadata.max.age.ms", "1000");
72 props.put("key.deserializer", StringDeserializer.class.getName());
73 props.put("value.deserializer", StringDeserializer.class.getName());
75 this.consumer = new KafkaConsumer<>(props);
77 log.info("{} - Subscribing to topic {}", id, topic);
78 consumer.subscribe(Arrays.asList(topic));
80 seen = new HashMap<>();
84 ConsumerRecords<String, String> records =
85 consumer.poll(Duration.ofSeconds(1));
87 // Do something with the data...
88 log.info("{} - Received {} messages", id, records.count());
89 for (ConsumerRecord<String, String> record : records)
93 "{} - {}: {}/{} - {}={}",
102 Integer partition = record.partition();
103 String key = record.key() == null ? "NULL" : record.key();
105 if (!seen.containsKey(partition))
106 seen.put(partition, new HashMap<>());
108 Map<String, Integer> byKey = seen.get(partition);
110 if (!byKey.containsKey(key))
113 int seenByKey = byKey.get(key);
115 byKey.put(key, seenByKey);
119 catch(WakeupException e)
121 log.info("{} - RIIING!", id);
126 log.error("{} - Unexpected error: {}", id, e.toString(), e);
131 log.info("{} - Closing the KafkaConsumer", id);
134 for (Integer partition : seen.keySet())
136 Map<String, Integer> byKey = seen.get(partition);
137 for (String key : byKey.keySet())
140 "{} - Seen {} messages for partition={}|key={}",
149 log.info("{} - Consumer-Thread exiting", id);
153 public Map<Integer, Map<String, Integer>> getSeen()
158 private void shutdown()
163 private void shutdown(Exception e)
184 throw new IllegalStateException("Consumer instance " + id + " is already running!");
186 log.info("{} - Starting - consumed {} messages before", id, consumed);
189 executor.submit(this);
197 public synchronized void stop() throws ExecutionException, InterruptedException
203 throw new IllegalStateException("Consumer instance " + id + " is not running!");
205 log.info("{} - Stopping", id);
208 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
217 public void destroy() throws ExecutionException, InterruptedException
219 log.info("{} - Destroy!", id);
224 catch (IllegalStateException e)
226 log.info("{} - Was already stopped", id);
230 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
234 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
238 public boolean running()
251 public Optional<Exception> exitStatus()
257 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
259 return Optional.ofNullable(exception);