1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
6 import org.apache.kafka.clients.consumer.ConsumerRecords;
7 import org.apache.kafka.clients.consumer.KafkaConsumer;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.WakeupException;
10 import org.apache.kafka.common.serialization.StringDeserializer;
12 import javax.annotation.PreDestroy;
13 import java.time.Duration;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.ExecutorService;
17 import java.util.concurrent.locks.Condition;
18 import java.util.concurrent.locks.Lock;
19 import java.util.concurrent.locks.ReentrantLock;
23 public class EndlessConsumer implements Runnable
25 private final ExecutorService executor;
26 private final PartitionStatisticsRepository repository;
27 private final String bootstrapServer;
28 private final String groupId;
29 private final String id;
30 private final String topic;
31 private final String autoOffsetReset;
33 private final Lock lock = new ReentrantLock();
34 private final Condition condition = lock.newCondition();
35 private boolean running = false;
36 private Exception exception;
37 private long consumed = 0;
38 private KafkaConsumer<String, String> consumer = null;
41 private final Map<Integer, Map<String, Integer>> seen = new HashMap<>();
44 public EndlessConsumer(
45 ExecutorService executor,
46 PartitionStatisticsRepository repository,
47 String bootstrapServer,
51 String autoOffsetReset)
53 this.executor = executor;
54 this.repository = repository;
55 this.bootstrapServer = bootstrapServer;
56 this.groupId = groupId;
59 this.autoOffsetReset = autoOffsetReset;
67 Properties props = new Properties();
68 props.put("bootstrap.servers", bootstrapServer);
69 props.put("group.id", groupId);
70 props.put("client.id", id);
71 props.put("auto.offset.reset", autoOffsetReset);
72 props.put("metadata.max.age.ms", "1000");
73 props.put("key.deserializer", StringDeserializer.class.getName());
74 props.put("value.deserializer", StringDeserializer.class.getName());
76 this.consumer = new KafkaConsumer<>(props);
78 log.info("{} - Subscribing to topic {}", id, topic);
79 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
82 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
84 partitions.forEach(tp ->
86 log.info("{} - removing partition: {}", id, tp);
87 Map<String, Integer> removed = seen.remove(tp.partition());
88 for (String key : removed.keySet())
91 "{} - Seen {} messages for partition={}|key={}",
97 repository.save(new StatisticsDocument(tp.partition(), removed));
102 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
104 partitions.forEach(tp ->
106 log.info("{} - adding partition: {}", id, tp);
110 .findById(Integer.toString(tp.partition()))
111 .map(document -> document.statistics)
112 .orElse(new HashMap<>()));
119 ConsumerRecords<String, String> records =
120 consumer.poll(Duration.ofSeconds(1));
122 // Do something with the data...
123 log.info("{} - Received {} messages", id, records.count());
124 for (ConsumerRecord<String, String> record : records)
128 "{} - {}: {}/{} - {}={}",
137 Integer partition = record.partition();
138 String key = record.key() == null ? "NULL" : record.key();
139 Map<String, Integer> byKey = seen.get(partition);
141 if (!byKey.containsKey(key))
144 int seenByKey = byKey.get(key);
146 byKey.put(key, seenByKey);
150 catch(WakeupException e)
152 log.info("{} - RIIING!", id);
157 log.error("{} - Unexpected error: {}", id, e.toString(), e);
162 log.info("{} - Closing the KafkaConsumer", id);
164 log.info("{} - Consumer-Thread exiting", id);
168 private void shutdown()
173 private void shutdown(Exception e)
188 public Map<Integer, Map<String, Integer>> getSeen()
199 throw new IllegalStateException("Consumer instance " + id + " is already running!");
201 log.info("{} - Starting - consumed {} messages before", id, consumed);
204 executor.submit(this);
212 public synchronized void stop() throws ExecutionException, InterruptedException
218 throw new IllegalStateException("Consumer instance " + id + " is not running!");
220 log.info("{} - Stopping", id);
223 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
232 public void destroy() throws ExecutionException, InterruptedException
234 log.info("{} - Destroy!", id);
239 catch (IllegalStateException e)
241 log.info("{} - Was already stopped", id);
245 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
249 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
253 public boolean running()
266 public Optional<Exception> exitStatus()
272 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
274 return Optional.ofNullable(exception);