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.Future;
18 import java.util.concurrent.atomic.AtomicBoolean;
22 public class EndlessConsumer implements Runnable
24 private final ExecutorService executor;
25 private final PartitionStatisticsRepository repository;
26 private final String bootstrapServer;
27 private final String groupId;
28 private final String id;
29 private final String topic;
30 private final String autoOffsetReset;
32 private AtomicBoolean running = new AtomicBoolean();
33 private long consumed = 0;
34 private KafkaConsumer<String, String> consumer = null;
35 private Future<?> future = null;
37 private final Map<Integer, Map<String, Integer>> seen = new HashMap<>();
40 public EndlessConsumer(
41 ExecutorService executor,
42 PartitionStatisticsRepository repository,
43 String bootstrapServer,
47 String autoOffsetReset)
49 this.executor = executor;
50 this.repository = repository;
51 this.bootstrapServer = bootstrapServer;
52 this.groupId = groupId;
55 this.autoOffsetReset = autoOffsetReset;
63 Properties props = new Properties();
64 props.put("bootstrap.servers", bootstrapServer);
65 props.put("group.id", groupId);
66 props.put("client.id", id);
67 props.put("enable.auto.commit", false);
68 props.put("auto.offset.reset", autoOffsetReset);
69 props.put("metadata.max.age.ms", "1000");
70 props.put("key.deserializer", StringDeserializer.class.getName());
71 props.put("value.deserializer", StringDeserializer.class.getName());
73 this.consumer = new KafkaConsumer<>(props);
75 log.info("{} - Subscribing to topic {}", id, topic);
76 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
79 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
81 partitions.forEach(tp ->
83 log.info("{} - removing partition: {}", id, tp);
84 Map<String, Integer> removed = seen.remove(tp.partition());
85 for (String key : removed.keySet())
88 "{} - Seen {} messages for partition={}|key={}",
94 repository.save(new StatisticsDocument(tp.partition(), removed, consumer.position(tp)));
99 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
101 partitions.forEach(tp ->
103 log.info("{} - adding partition: {}", id, tp);
104 StatisticsDocument document =
106 .findById(Integer.toString(tp.partition()))
107 .orElse(new StatisticsDocument(tp.partition()));
108 consumer.seek(tp, document.offset);
109 seen.put(tp.partition(), document.statistics);
116 ConsumerRecords<String, String> records =
117 consumer.poll(Duration.ofSeconds(1));
119 // Do something with the data...
120 log.info("{} - Received {} messages", id, records.count());
121 for (ConsumerRecord<String, String> record : records)
125 "{} - {}: {}/{} - {}={}",
134 Integer partition = record.partition();
135 String key = record.key() == null ? "NULL" : record.key();
136 Map<String, Integer> byKey = seen.get(partition);
138 if (!byKey.containsKey(key))
141 int seenByKey = byKey.get(key);
143 byKey.put(key, seenByKey);
146 seen.forEach((partiton, statistics) -> repository.save(
147 new StatisticsDocument(
150 consumer.position(new TopicPartition(topic, partiton)))));
153 catch(WakeupException e)
155 log.info("{} - RIIING!", id);
159 log.error("{} - Unexpected error: {}", id, e.toString(), e);
160 running.set(false); // Mark the instance as not running
164 log.info("{} - Closing the KafkaConsumer", id);
166 log.info("{} - Consumer-Thread exiting", id);
170 public Map<Integer, Map<String, Integer>> getSeen()
175 public synchronized void start()
177 boolean stateChanged = running.compareAndSet(false, true);
179 throw new RuntimeException("Consumer instance " + id + " is already running!");
181 log.info("{} - Starting - consumed {} messages before", id, consumed);
182 future = executor.submit(this);
185 public synchronized void stop() throws ExecutionException, InterruptedException
187 boolean stateChanged = running.compareAndSet(true, false);
189 throw new RuntimeException("Consumer instance " + id + " is not running!");
191 log.info("{} - Stopping", id);
194 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
198 public void destroy() throws ExecutionException, InterruptedException
200 log.info("{} - Destroy!", id);
205 catch (IllegalStateException e)
207 log.info("{} - Was already stopped", id);
211 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);