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("enable.auto.commit", false);
72 props.put("auto.offset.reset", autoOffsetReset);
73 props.put("metadata.max.age.ms", "1000");
74 props.put("key.deserializer", StringDeserializer.class.getName());
75 props.put("value.deserializer", StringDeserializer.class.getName());
77 this.consumer = new KafkaConsumer<>(props);
79 log.info("{} - Subscribing to topic {}", id, topic);
80 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
83 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
85 partitions.forEach(tp ->
87 log.info("{} - removing partition: {}", id, tp);
88 Map<String, Integer> removed = seen.remove(tp.partition());
89 for (String key : removed.keySet())
92 "{} - Seen {} messages for partition={}|key={}",
98 repository.save(new StatisticsDocument(tp.partition(), removed, consumer.position(tp)));
103 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
105 partitions.forEach(tp ->
107 log.info("{} - adding partition: {}", id, tp);
108 StatisticsDocument document =
110 .findById(Integer.toString(tp.partition()))
111 .orElse(new StatisticsDocument(tp.partition()));
112 consumer.seek(tp, document.offset);
113 seen.put(tp.partition(), document.statistics);
120 ConsumerRecords<String, String> records =
121 consumer.poll(Duration.ofSeconds(1));
123 // Do something with the data...
124 log.info("{} - Received {} messages", id, records.count());
125 for (ConsumerRecord<String, String> record : records)
129 "{} - {}: {}/{} - {}={}",
138 Integer partition = record.partition();
139 String key = record.key() == null ? "NULL" : record.key();
140 Map<String, Integer> byKey = seen.get(partition);
142 if (!byKey.containsKey(key))
145 int seenByKey = byKey.get(key);
147 byKey.put(key, seenByKey);
150 seen.forEach((partiton, statistics) -> repository.save(
151 new StatisticsDocument(
154 consumer.position(new TopicPartition(topic, partiton)))));
157 catch(WakeupException e)
159 log.info("{} - RIIING!", id);
164 log.error("{} - Unexpected error: {}", id, e.toString(), e);
169 log.info("{} - Closing the KafkaConsumer", id);
171 log.info("{} - Consumer-Thread exiting", id);
175 private void shutdown()
180 private void shutdown(Exception e)
195 public Map<Integer, Map<String, Integer>> getSeen()
206 throw new IllegalStateException("Consumer instance " + id + " is already running!");
208 log.info("{} - Starting - consumed {} messages before", id, consumed);
211 executor.submit(this);
219 public synchronized void stop() throws ExecutionException, InterruptedException
225 throw new IllegalStateException("Consumer instance " + id + " is not running!");
227 log.info("{} - Stopping", id);
230 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
239 public void destroy() throws ExecutionException, InterruptedException
241 log.info("{} - Destroy!", id);
246 catch (IllegalStateException e)
248 log.info("{} - Was already stopped", id);
252 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
256 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
260 public boolean running()
273 public Optional<Exception> exitStatus()
279 throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
281 return Optional.ofNullable(exception);