Wenn kein gespeicherter Offset vorliegt, auto.offset.reset von Kafka nutzen
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
1 package de.juplo.kafka;
2
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.*;
6 import org.apache.kafka.common.TopicPartition;
7 import org.apache.kafka.common.errors.RecordDeserializationException;
8 import org.apache.kafka.common.errors.WakeupException;
9
10 import javax.annotation.PreDestroy;
11 import java.time.Duration;
12 import java.util.*;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.ExecutorService;
15 import java.util.concurrent.locks.Condition;
16 import java.util.concurrent.locks.Lock;
17 import java.util.concurrent.locks.ReentrantLock;
18
19
20 @Slf4j
21 @RequiredArgsConstructor
22 public class EndlessConsumer<K, V> implements ConsumerRebalanceListener, Runnable
23 {
24   private final ExecutorService executor;
25   private final PartitionStatisticsRepository repository;
26   private final String id;
27   private final String topic;
28   private final Consumer<K, V> consumer;
29   private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
30
31   private final Lock lock = new ReentrantLock();
32   private final Condition condition = lock.newCondition();
33   private boolean running = false;
34   private Exception exception;
35   private long consumed = 0;
36
37   private final Map<Integer, Map<String, Long>> seen = new HashMap<>();
38
39
40   @Override
41   public void onPartitionsRevoked(Collection<TopicPartition> partitions)
42   {
43     partitions.forEach(tp ->
44     {
45       Integer partition = tp.partition();
46       Long newOffset = consumer.position(tp);
47       log.info(
48           "{} - removing partition: {}, offset of next message {})",
49           id,
50           partition,
51           newOffset);
52       Map<String, Long> removed = seen.remove(partition);
53       for (String key : removed.keySet())
54       {
55         log.info(
56             "{} - Seen {} messages for partition={}|key={}",
57             id,
58             removed.get(key),
59             partition,
60             key);
61       }
62       repository.save(new StatisticsDocument(partition, removed, consumer.position(tp)));
63     });
64   }
65
66   @Override
67   public void onPartitionsAssigned(Collection<TopicPartition> partitions)
68   {
69     partitions.forEach(tp ->
70     {
71       Integer partition = tp.partition();
72       Long offset = consumer.position(tp);
73       log.info("{} - adding partition: {}, offset={}", id, partition, offset);
74       StatisticsDocument document =
75           repository
76               .findById(Integer.toString(partition))
77               .orElse(new StatisticsDocument(partition));
78       if (document.offset >= 0)
79       {
80         // Only seek, if a stored offset was found
81         // Otherwise: Use initial offset, generated by Kafka
82         consumer.seek(tp, document.offset);
83       }
84       seen.put(partition, document.statistics);
85     });
86   }
87
88
89   @Override
90   public void run()
91   {
92     try
93     {
94       log.info("{} - Subscribing to topic {}", id, topic);
95       consumer.subscribe(Arrays.asList(topic), this);
96
97       while (true)
98       {
99         ConsumerRecords<K, V> records =
100             consumer.poll(Duration.ofSeconds(1));
101
102         // Do something with the data...
103         log.info("{} - Received {} messages", id, records.count());
104         for (ConsumerRecord<K, V> record : records)
105         {
106           log.info(
107               "{} - {}: {}/{} - {}={}",
108               id,
109               record.offset(),
110               record.topic(),
111               record.partition(),
112               record.key(),
113               record.value()
114           );
115
116           handler.accept(record);
117
118           consumed++;
119
120           Integer partition = record.partition();
121           String key = record.key() == null ? "NULL" : record.key().toString();
122           Map<String, Long> byKey = seen.get(partition);
123
124           if (!byKey.containsKey(key))
125             byKey.put(key, 0l);
126
127           long seenByKey = byKey.get(key);
128           seenByKey++;
129           byKey.put(key, seenByKey);
130         }
131
132         seen.forEach((partiton, statistics) -> repository.save(
133             new StatisticsDocument(
134                 partiton,
135                 statistics,
136                 consumer.position(new TopicPartition(topic, partiton)))));
137       }
138     }
139     catch(WakeupException e)
140     {
141       log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
142       shutdown();
143     }
144     catch(RecordDeserializationException e)
145     {
146       TopicPartition tp = e.topicPartition();
147       long offset = e.offset();
148       log.error(
149           "{} - Could not deserialize  message on topic {} with offset={}: {}",
150           id,
151           tp,
152           offset,
153           e.getCause().toString());
154
155       shutdown(e);
156     }
157     catch(Exception e)
158     {
159       log.error("{} - Unexpected error: {}", id, e.toString(), e);
160       shutdown(e);
161     }
162     finally
163     {
164       log.info("{} - Consumer-Thread exiting", id);
165     }
166   }
167
168   private void shutdown()
169   {
170     shutdown(null);
171   }
172
173   private void shutdown(Exception e)
174   {
175     lock.lock();
176     try
177     {
178       try
179       {
180         log.info("{} - Unsubscribing from topic {}", id, topic);
181         consumer.unsubscribe();
182       }
183       catch (Exception ue)
184       {
185         log.error(
186             "{} - Error while unsubscribing from topic {}: {}",
187             id,
188             topic,
189             ue.toString());
190       }
191       finally
192       {
193         running = false;
194         exception = e;
195         condition.signal();
196       }
197     }
198     finally
199     {
200       lock.unlock();
201     }
202   }
203
204   public Map<Integer, Map<String, Long>> getSeen()
205   {
206     return seen;
207   }
208
209   public void start()
210   {
211     lock.lock();
212     try
213     {
214       if (running)
215         throw new IllegalStateException("Consumer instance " + id + " is already running!");
216
217       log.info("{} - Starting - consumed {} messages before", id, consumed);
218       running = true;
219       exception = null;
220       executor.submit(this);
221     }
222     finally
223     {
224       lock.unlock();
225     }
226   }
227
228   public synchronized void stop() throws ExecutionException, InterruptedException
229   {
230     lock.lock();
231     try
232     {
233       if (!running)
234         throw new IllegalStateException("Consumer instance " + id + " is not running!");
235
236       log.info("{} - Stopping", id);
237       consumer.wakeup();
238       condition.await();
239       log.info("{} - Stopped - consumed {} messages so far", id, consumed);
240     }
241     finally
242     {
243       lock.unlock();
244     }
245   }
246
247   @PreDestroy
248   public void destroy() throws ExecutionException, InterruptedException
249   {
250     log.info("{} - Destroy!", id);
251     log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
252   }
253
254   public boolean running()
255   {
256     lock.lock();
257     try
258     {
259       return running;
260     }
261     finally
262     {
263       lock.unlock();
264     }
265   }
266
267   public Optional<Exception> exitStatus()
268   {
269     lock.lock();
270     try
271     {
272       if (running)
273         throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
274
275       return Optional.ofNullable(exception);
276     }
277     finally
278     {
279       lock.unlock();
280     }
281   }
282 }