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