6e460b4387642f59cdf1bfb7284368f9c227ab35
[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   private final Map<Integer, Long> lastOffsets = new HashMap<>();
39
40
41   @Override
42   public void onPartitionsRevoked(Collection<TopicPartition> partitions)
43   {
44     partitions.forEach(tp ->
45     {
46       Integer partition = tp.partition();
47       Long newOffset = consumer.position(tp);
48       Long oldOffset = lastOffsets.remove(partition);
49       log.info(
50           "{} - removing partition: {}, consumed {} records (offset {} -> {})",
51           id,
52           partition,
53           newOffset - oldOffset,
54           oldOffset,
55           newOffset);
56       Map<String, Long> removed = seen.remove(partition);
57       for (String key : removed.keySet())
58       {
59         log.info(
60             "{} - Seen {} messages for partition={}|key={}",
61             id,
62             removed.get(key),
63             partition,
64             key);
65       }
66       repository.save(new StatisticsDocument(partition, removed, consumer.position(tp)));
67     });
68   }
69
70   @Override
71   public void onPartitionsAssigned(Collection<TopicPartition> partitions)
72   {
73     partitions.forEach(tp ->
74     {
75       Integer partition = tp.partition();
76       Long offset = consumer.position(tp);
77       log.info("{} - adding partition: {}, offset={}", id, partition, offset);
78       StatisticsDocument document =
79           repository
80               .findById(Integer.toString(partition))
81               .orElse(new StatisticsDocument(partition));
82       consumer.seek(tp, document.offset);
83       lastOffsets.put(partition, document.offset);
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     try
252     {
253       stop();
254     }
255     catch (IllegalStateException e)
256     {
257       log.info("{} - Was already stopped", id);
258     }
259     catch (Exception e)
260     {
261       log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
262     }
263     finally
264     {
265       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
266     }
267   }
268
269   public boolean running()
270   {
271     lock.lock();
272     try
273     {
274       return running;
275     }
276     finally
277     {
278       lock.unlock();
279     }
280   }
281
282   public Optional<Exception> exitStatus()
283   {
284     lock.lock();
285     try
286     {
287       if (running)
288         throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
289
290       return Optional.ofNullable(exception);
291     }
292     finally
293     {
294       lock.unlock();
295     }
296   }
297 }