`commitAsync()` in `onPartitionsRevoked()`
[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 Runnable
23 {
24   private final ExecutorService executor;
25   private final String id;
26   private final String topic;
27   private final Consumer<K, V> consumer;
28   private final ConsumerRebalanceListener rebalanceListener;
29   private final RecordHandler<K, V> recordHandler;
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
38
39   @Override
40   public void run()
41   {
42     try
43     {
44       log.info("{} - Subscribing to topic {}", id, topic);
45       consumer.subscribe(Arrays.asList(topic), rebalanceListener);
46
47       while (true)
48       {
49         ConsumerRecords<K, V> records =
50             consumer.poll(Duration.ofSeconds(1));
51
52         // Do something with the data...
53         log.info("{} - Received {} messages", id, records.count());
54         for (ConsumerRecord<K, V> record : records)
55         {
56           log.info(
57               "{} - {}: {}/{} - {}={}",
58               id,
59               record.offset(),
60               record.topic(),
61               record.partition(),
62               record.key(),
63               record.value()
64           );
65
66           recordHandler.accept(record);
67
68           consumed++;
69         }
70       }
71     }
72     catch(WakeupException e)
73     {
74       log.info("{} - RIIING! Request to stop consumption.", id);
75       shutdown();
76     }
77     catch(RecordDeserializationException e)
78     {
79       TopicPartition tp = e.topicPartition();
80       long offset = e.offset();
81       log.error(
82           "{} - Could not deserialize  message on topic {} with offset={}: {}",
83           id,
84           tp,
85           offset,
86           e.getCause().toString());
87
88       shutdown(e);
89     }
90     catch(Exception e)
91     {
92       log.error("{} - Unexpected error: {}", id, e.toString(), e);
93       shutdown(e);
94     }
95     finally
96     {
97       log.info("{} - Consumer-Thread exiting", id);
98     }
99   }
100
101   private void shutdown()
102   {
103     shutdown(null);
104   }
105
106   private void shutdown(Exception e)
107   {
108     lock.lock();
109     try
110     {
111       try
112       {
113         log.info("{} - Unsubscribing from topic {}", id, topic);
114         consumer.unsubscribe();
115       }
116       catch (Exception ue)
117       {
118         log.error(
119             "{} - Error while unsubscribing from topic {}: {}",
120             id,
121             topic,
122             ue.toString());
123       }
124       finally
125       {
126         running = false;
127         exception = e;
128         condition.signal();
129       }
130     }
131     finally
132     {
133       lock.unlock();
134     }
135   }
136
137   public void start()
138   {
139     lock.lock();
140     try
141     {
142       if (running)
143         throw new IllegalStateException("Consumer instance " + id + " is already running!");
144
145       log.info("{} - Starting - consumed {} messages before", id, consumed);
146       running = true;
147       exception = null;
148       executor.submit(this);
149     }
150     finally
151     {
152       lock.unlock();
153     }
154   }
155
156   public synchronized void stop() throws InterruptedException
157   {
158     lock.lock();
159     try
160     {
161       if (!running)
162         throw new IllegalStateException("Consumer instance " + id + " is not running!");
163
164       log.info("{} - Stopping", id);
165       consumer.wakeup();
166       condition.await();
167       log.info("{} - Stopped - consumed {} messages so far", id, consumed);
168     }
169     finally
170     {
171       lock.unlock();
172     }
173   }
174
175   @PreDestroy
176   public void destroy() throws ExecutionException, InterruptedException
177   {
178     log.info("{} - Destroy!", id);
179     log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
180   }
181
182   public boolean running()
183   {
184     lock.lock();
185     try
186     {
187       return running;
188     }
189     finally
190     {
191       lock.unlock();
192     }
193   }
194
195   public Optional<Exception> exitStatus()
196   {
197     lock.lock();
198     try
199     {
200       if (running)
201         throw new IllegalStateException("No exit-status available: Consumer instance " + id + " is running!");
202
203       return Optional.ofNullable(exception);
204     }
205     finally
206     {
207       lock.unlock();
208     }
209   }
210 }