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 String bootstrapServer;
27 private final String groupId;
28 private final String id;
29 private final String topic;
30 private final String autoOffsetReset;
32 private final Lock lock = new ReentrantLock();
33 private final Condition condition = lock.newCondition();
34 private boolean running = false;
35 private long consumed = 0;
36 private KafkaConsumer<String, String> consumer = null;
39 private final Map<Integer, Map<String, Integer>> seen = new HashMap<>();
42 public EndlessConsumer(
43 ExecutorService executor,
44 String bootstrapServer,
48 String autoOffsetReset)
50 this.executor = executor;
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("auto.offset.reset", autoOffsetReset);
68 props.put("metadata.max.age.ms", "1000");
69 props.put("key.deserializer", StringDeserializer.class.getName());
70 props.put("value.deserializer", StringDeserializer.class.getName());
72 this.consumer = new KafkaConsumer<>(props);
74 log.info("{} - Subscribing to topic {}", id, topic);
75 consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
78 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
80 partitions.forEach(tp ->
82 log.info("{} - removing partition: {}", id, tp);
83 Map<String, Integer> removed = seen.remove(tp.partition());
84 for (String key : removed.keySet())
87 "{} - Seen {} messages for partition={}|key={}",
97 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
99 partitions.forEach(tp ->
101 log.info("{} - adding partition: {}", id, tp);
102 seen.put(tp.partition(), new HashMap<>());
109 ConsumerRecords<String, String> records =
110 consumer.poll(Duration.ofSeconds(1));
112 // Do something with the data...
113 log.info("{} - Received {} messages", id, records.count());
114 for (ConsumerRecord<String, String> record : records)
118 "{} - {}: {}/{} - {}={}",
127 Integer partition = record.partition();
128 String key = record.key() == null ? "NULL" : record.key();
129 Map<String, Integer> byKey = seen.get(partition);
131 if (!byKey.containsKey(key))
134 int seenByKey = byKey.get(key);
136 byKey.put(key, seenByKey);
140 catch(WakeupException e)
142 log.info("{} - RIIING!", id);
147 log.error("{} - Unexpected error: {}", id, e.toString(), e);
152 log.info("{} - Closing the KafkaConsumer", id);
154 log.info("{} - Consumer-Thread exiting", id);
158 private void shutdown()
172 public Map<Integer, Map<String, Integer>> getSeen()
183 throw new IllegalStateException("Consumer instance " + id + " is already running!");
185 log.info("{} - Starting - consumed {} messages before", id, consumed);
187 executor.submit(this);
195 public synchronized void stop() throws ExecutionException, InterruptedException
201 throw new IllegalStateException("Consumer instance " + id + " is not running!");
203 log.info("{} - Stopping", id);
206 log.info("{} - Stopped - consumed {} messages so far", id, consumed);
215 public void destroy() throws ExecutionException, InterruptedException
217 log.info("{} - Destroy!", id);
222 catch (IllegalStateException e)
224 log.info("{} - Was already stopped", id);
228 log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
232 log.info("{}: Consumed {} messages in total, exiting!", id, consumed);