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, Integer>> 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 -> seen.remove(tp.partition()));
81 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
83 partitions.forEach(tp -> seen.put(tp.partition(), new HashMap<>()));
89 ConsumerRecords<String, String> records =
90 consumer.poll(Duration.ofSeconds(1));
92 // Do something with the data...
93 log.info("{} - Received {} messages", id, records.count());
94 for (ConsumerRecord<String, String> record : records)
98 "{} - {}: {}/{} - {}={}",
107 Integer partition = record.partition();
108 String key = record.key() == null ? "NULL" : record.key();
109 Map<String, Integer> byKey = seen.get(partition);
111 if (!byKey.containsKey(key))
114 int seenByKey = byKey.get(key);
116 byKey.put(key, seenByKey);
120 catch(WakeupException e)
122 log.info("{} - RIIING!", id);
126 log.error("{} - Unexpected error: {}", id, e.toString(), e);
127 running.set(false); // Mark the instance as not running
131 log.info("{} - Closing the KafkaConsumer", id);
134 for (Integer partition : seen.keySet())
136 Map<String, Integer> byKey = seen.get(partition);
137 for (String key : byKey.keySet())
140 "{} - Seen {} messages for partition={}|key={}",
148 log.info("{} - Consumer-Thread exiting", id);
152 public Map<Integer, Map<String, Integer>> getSeen()
157 public synchronized void start()
159 boolean stateChanged = running.compareAndSet(false, true);
161 throw new RuntimeException("Consumer instance " + id + " is already running!");
163 log.info("{} - Starting - consumed {} messages before", id, consumed);
164 future = executor.submit(this);
167 public synchronized void stop() throws ExecutionException, InterruptedException
169 boolean stateChanged = running.compareAndSet(true, false);
171 throw new RuntimeException("Consumer instance " + id + " is not running!");
173 log.info("{} - Stopping", id);
176 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
180 public void destroy() throws ExecutionException, InterruptedException
182 log.info("{} - Destroy!", id);
187 catch (IllegalStateException e)
189 log.info("{} - Was already stopped", id);
193 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);