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<Integer, Map<String, Long>> seen = new HashMap<>();
37 private final Map<Integer, Long> offsets = new HashMap<>();
40 public EndlessConsumer(
41 ExecutorService executor,
42 String bootstrapServer,
46 String autoOffsetReset)
48 this.executor = executor;
49 this.bootstrapServer = bootstrapServer;
50 this.groupId = groupId;
53 this.autoOffsetReset = autoOffsetReset;
61 Properties props = new Properties();
62 props.put("bootstrap.servers", bootstrapServer);
63 props.put("group.id", groupId);
64 props.put("client.id", id);
65 props.put("auto.offset.reset", autoOffsetReset);
66 props.put("metadata.max.age.ms", "1000");
67 props.put("key.deserializer", StringDeserializer.class.getName());
68 props.put("value.deserializer", StringDeserializer.class.getName());
70 this.consumer = new KafkaConsumer<>(props);
72 log.info("{} - Subscribing to topic {}", id, topic);
73 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
76 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
78 partitions.forEach(tp ->
80 Integer partition = tp.partition();
81 Long newOffset = consumer.position(tp);
82 Long oldOffset = offsets.remove(partition);
84 "{} - removing partition: {}, consumed {} records (offset {} -> {})",
87 newOffset - oldOffset,
90 Map<String, Long> removed = seen.remove(partition);
91 for (String key : removed.keySet())
94 "{} - Seen {} messages for partition={}|key={}",
104 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
106 partitions.forEach(tp ->
108 Integer partition = tp.partition();
109 Long offset = consumer.position(tp);
110 log.info("{} - adding partition: {}, offset={}", id, partition, offset);
111 offsets.put(partition, offset);
112 seen.put(partition, 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, Long> byKey = seen.get(partition);
141 if (!byKey.containsKey(key))
144 long seenByKey = byKey.get(key);
146 byKey.put(key, seenByKey);
150 catch(WakeupException e)
152 log.info("{} - RIIING!", id);
156 log.error("{} - Unexpected error: {}", id, e.toString(), e);
157 running.set(false); // Mark the instance as not running
161 log.info("{} - Closing the KafkaConsumer", id);
163 log.info("{} - Consumer-Thread exiting", id);
167 public Map<Integer, Map<String, Long>> getSeen()
172 public synchronized void start()
174 boolean stateChanged = running.compareAndSet(false, true);
176 throw new RuntimeException("Consumer instance " + id + " is already running!");
178 log.info("{} - Starting - consumed {} messages before", id, consumed);
179 future = executor.submit(this);
182 public Optional<Long> getOffset(Integer partition)
184 return Optional.ofNullable(offsets.get(partition));
187 public synchronized void stop() throws ExecutionException, InterruptedException
189 boolean stateChanged = running.compareAndSet(true, false);
191 throw new RuntimeException("Consumer instance " + id + " is not running!");
193 log.info("{} - Stopping", id);
196 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
200 public void destroy() throws ExecutionException, InterruptedException
202 log.info("{} - Destroy!", id);
207 catch (IllegalStateException e)
209 log.info("{} - Was already stopped", id);
213 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);