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 String bootstrapServer;
26 private final String groupId;
27 private final String id;
28 private final String topic;
29 private final String autoOffsetReset;
31 private AtomicBoolean running = new AtomicBoolean();
32 private long consumed = 0;
33 private KafkaConsumer<String, String> consumer = null;
34 private Future<?> future = null;
36 private final Map<TopicPartition, PartitionStatistics> seen = new HashMap<>();
39 public EndlessConsumer(
40 ExecutorService executor,
41 String bootstrapServer,
45 String autoOffsetReset)
47 this.executor = executor;
48 this.bootstrapServer = bootstrapServer;
49 this.groupId = groupId;
52 this.autoOffsetReset = autoOffsetReset;
60 Properties props = new Properties();
61 props.put("bootstrap.servers", bootstrapServer);
62 props.put("group.id", groupId);
63 props.put("client.id", id);
64 props.put("auto.offset.reset", autoOffsetReset);
65 props.put("metadata.max.age.ms", "1000");
66 props.put("key.deserializer", StringDeserializer.class.getName());
67 props.put("value.deserializer", StringDeserializer.class.getName());
69 this.consumer = new KafkaConsumer<>(props);
71 log.info("{} - Subscribing to topic {}", id, topic);
72 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
75 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
77 partitions.forEach(tp ->
79 log.info("{} - removing partition: {}", id, tp);
80 PartitionStatistics removed = seen.remove(tp);
81 for (KeyCounter counter : removed.getStatistics())
84 "{} - Seen {} messages for partition={}|key={}",
87 removed.getPartition(),
94 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
96 partitions.forEach(tp ->
98 log.info("{} - adding partition: {}", id, tp);
99 seen.put(tp, new PartitionStatistics(tp));
106 ConsumerRecords<String, String> records =
107 consumer.poll(Duration.ofSeconds(1));
109 // Do something with the data...
110 log.info("{} - Received {} messages", id, records.count());
111 for (ConsumerRecord<String, String> record : records)
115 "{} - {}: {}/{} - {}={}",
124 TopicPartition partition = new TopicPartition(record.topic(), record.partition());
125 String key = record.key() == null ? "NULL" : record.key();
126 seen.get(partition).increment(key);
130 catch(WakeupException e)
132 log.info("{} - RIIING!", id);
136 log.error("{} - Unexpected error: {}", id, e.toString(), e);
137 running.set(false); // Mark the instance as not running
141 log.info("{} - Closing the KafkaConsumer", id);
143 log.info("{} - Consumer-Thread exiting", id);
147 public Map<TopicPartition, PartitionStatistics> getSeen()
152 public synchronized void start()
154 boolean stateChanged = running.compareAndSet(false, true);
156 throw new RuntimeException("Consumer instance " + id + " is already running!");
158 log.info("{} - Starting - consumed {} messages before", id, consumed);
159 future = executor.submit(this);
162 public synchronized void stop() throws ExecutionException, InterruptedException
164 boolean stateChanged = running.compareAndSet(true, false);
166 throw new RuntimeException("Consumer instance " + id + " is not running!");
168 log.info("{} - Stopping", id);
171 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
175 public void destroy() throws ExecutionException, InterruptedException
177 log.info("{} - Destroy!", id);
182 catch (IllegalStateException e)
184 log.info("{} - Was already stopped", id);
188 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);