Fehler im Shutdown-Code korrigiert: Shutdown von `EndlessConsumer` zu spät
[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       consumer.seek(tp, document.offset);
79       seen.put(partition, document.statistics);
80     });
81   }
82
83
84   @Override
85   public void run()
86   {
87     try
88     {
89       log.info("{} - Subscribing to topic {}", id, topic);
90       consumer.subscribe(Arrays.asList(topic), this);
91
92       while (true)
93       {
94         ConsumerRecords<K, V> records =
95             consumer.poll(Duration.ofSeconds(1));
96
97         // Do something with the data...
98         log.info("{} - Received {} messages", id, records.count());
99         for (ConsumerRecord<K, V> record : records)
100         {
101           log.info(
102               "{} - {}: {}/{} - {}={}",
103               id,
104               record.offset(),
105               record.topic(),
106               record.partition(),
107               record.key(),
108               record.value()
109           );
110
111           handler.accept(record);
112
113           consumed++;
114
115           Integer partition = record.partition();
116           String key = record.key() == null ? "NULL" : record.key().toString();
117           Map<String, Long> byKey = seen.get(partition);
118
119           if (!byKey.containsKey(key))
120             byKey.put(key, 0l);
121
122           long seenByKey = byKey.get(key);
123           seenByKey++;
124           byKey.put(key, seenByKey);
125         }
126
127         seen.forEach((partiton, statistics) -> repository.save(
128             new StatisticsDocument(
129                 partiton,
130                 statistics,
131                 consumer.position(new TopicPartition(topic, partiton)))));
132       }
133     }
134     catch(WakeupException e)
135     {
136       log.info("{} - RIIING! Request to stop consumption - commiting current offsets!", id);
137       shutdown();
138     }
139     catch(RecordDeserializationException e)
140     {
141       TopicPartition tp = e.topicPartition();
142       long offset = e.offset();
143       log.error(
144           "{} - Could not deserialize  message on topic {} with offset={}: {}",
145           id,
146           tp,
147           offset,
148           e.getCause().toString());
149
150       shutdown(e);
151     }
152     catch(Exception e)
153     {
154       log.error("{} - Unexpected error: {}", id, e.toString(), e);
155       shutdown(e);
156     }
157     finally
158     {
159       log.info("{} - Consumer-Thread exiting", id);
160     }
161   }
162
163   private void shutdown()
164   {
165     shutdown(null);
166   }
167
168   private void shutdown(Exception e)
169   {
170     lock.lock();
171     try
172     {
173       try
174       {
175         log.info("{} - Unsubscribing from topic {}", id, topic);
176         consumer.unsubscribe();
177       }
178       catch (Exception ue)
179       {
180         log.error(
181             "{} - Error while unsubscribing from topic {}: {}",
182             id,
183             topic,
184             ue.toString());
185       }
186       finally
187       {
188         running = false;
189         exception = e;
190         condition.signal();
191       }
192     }
193     finally
194     {
195       lock.unlock();
196     }
197   }
198
199   public Map<Integer, Map<String, Long>> getSeen()
200   {
201     return seen;
202   }
203
204   public void start()
205   {
206     lock.lock();
207     try
208     {
209       if (running)
210         throw new IllegalStateException("Consumer instance " + id + " is already running!");
211
212       log.info("{} - Starting - consumed {} messages before", id, consumed);
213       running = true;
214       exception = null;
215       executor.submit(this);
216     }
217     finally
218     {
219       lock.unlock();
220     }
221   }
222
223   public synchronized void stop() throws ExecutionException, InterruptedException
224   {
225     lock.lock();
226     try
227     {
228       if (!running)
229         throw new IllegalStateException("Consumer instance " + id + " is not running!");
230
231       log.info("{} - Stopping", id);
232       consumer.wakeup();
233       condition.await();
234       log.info("{} - Stopped - consumed {} messages so far", id, consumed);
235     }
236     finally
237     {
238       lock.unlock();
239     }
240   }
241
242   @PreDestroy
243   public void destroy() throws ExecutionException, InterruptedException
244   {
245     log.info("{} - Destroy!", id);
246     log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
247   }
248
249   public boolean running()
250   {
251     lock.lock();
252     try
253     {
254       return running;
255     }
256     finally
257     {
258       lock.unlock();
259     }
260   }
261
262   public Optional<Exception> exitStatus()
263   {
264     lock.lock();
265     try
266     {
267       if (running)
268         throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
269
270       return Optional.ofNullable(exception);
271     }
272     finally
273     {
274       lock.unlock();
275     }
276   }
277 }