Rebalance-Listener anstatt Wegwerfen der Map
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
6 import org.apache.kafka.clients.consumer.ConsumerRecords;
7 import org.apache.kafka.clients.consumer.KafkaConsumer;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.WakeupException;
10 import org.apache.kafka.common.serialization.StringDeserializer;
11
12 import javax.annotation.PreDestroy;
13 import java.time.Duration;
14 import java.util.*;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.ExecutorService;
17 import java.util.concurrent.Future;
18 import java.util.concurrent.atomic.AtomicBoolean;
19
20
21 @Slf4j
22 public class EndlessConsumer implements Runnable
23 {
24   private final ExecutorService executor;
25   private final String bootstrapServer;
26   private final String groupId;
27   private final String id;
28   private final String topic;
29   private final String autoOffsetReset;
30
31   private AtomicBoolean running = new AtomicBoolean();
32   private long consumed = 0;
33   private KafkaConsumer<String, String> consumer = null;
34   private Future<?> future = null;
35
36   private final Map<Integer, Map<String, Integer>> seen = new HashMap<>();
37
38
39   public EndlessConsumer(
40       ExecutorService executor,
41       String bootstrapServer,
42       String groupId,
43       String clientId,
44       String topic,
45       String autoOffsetReset)
46   {
47     this.executor = executor;
48     this.bootstrapServer = bootstrapServer;
49     this.groupId = groupId;
50     this.id = clientId;
51     this.topic = topic;
52     this.autoOffsetReset = autoOffsetReset;
53   }
54
55   @Override
56   public void run()
57   {
58     try
59     {
60       Properties props = new Properties();
61       props.put("bootstrap.servers", bootstrapServer);
62       props.put("group.id", groupId);
63       props.put("client.id", id);
64       props.put("auto.offset.reset", autoOffsetReset);
65       props.put("metadata.max.age.ms", "1000");
66       props.put("key.deserializer", StringDeserializer.class.getName());
67       props.put("value.deserializer", StringDeserializer.class.getName());
68
69       this.consumer = new KafkaConsumer<>(props);
70
71       log.info("{} - Subscribing to topic {}", id, topic);
72       consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
73       {
74         @Override
75         public void onPartitionsRevoked(Collection<TopicPartition> partitions)
76         {
77           partitions.forEach(tp -> seen.remove(tp.partition()));
78         }
79
80         @Override
81         public void onPartitionsAssigned(Collection<TopicPartition> partitions)
82         {
83           partitions.forEach(tp -> seen.put(tp.partition(), new HashMap<>()));
84         }
85       });
86
87       while (true)
88       {
89         ConsumerRecords<String, String> records =
90             consumer.poll(Duration.ofSeconds(1));
91
92         // Do something with the data...
93         log.info("{} - Received {} messages", id, records.count());
94         for (ConsumerRecord<String, String> record : records)
95         {
96           consumed++;
97           log.info(
98               "{} - {}: {}/{} - {}={}",
99               id,
100               record.offset(),
101               record.topic(),
102               record.partition(),
103               record.key(),
104               record.value()
105           );
106
107           Integer partition = record.partition();
108           String key = record.key() == null ? "NULL" : record.key();
109           Map<String, Integer> byKey = seen.get(partition);
110
111           if (!byKey.containsKey(key))
112             byKey.put(key, 0);
113
114           int seenByKey = byKey.get(key);
115           seenByKey++;
116           byKey.put(key, seenByKey);
117         }
118       }
119     }
120     catch(WakeupException e)
121     {
122       log.info("{} - RIIING!", id);
123     }
124     catch(Exception e)
125     {
126       log.error("{} - Unexpected error: {}", id, e.toString(), e);
127       running.set(false); // Mark the instance as not running
128     }
129     finally
130     {
131       log.info("{} - Closing the KafkaConsumer", id);
132       consumer.close();
133
134       for (Integer partition : seen.keySet())
135       {
136         Map<String, Integer> byKey = seen.get(partition);
137         for (String key : byKey.keySet())
138         {
139           log.info(
140               "{} - Seen {} messages for partition={}|key={}",
141               id,
142               byKey.get(key),
143               partition,
144               key);
145         }
146       }
147
148       log.info("{} - Consumer-Thread exiting", id);
149     }
150   }
151
152   public Map<Integer, Map<String, Integer>> getSeen()
153   {
154     return seen;
155   }
156
157   public synchronized void start()
158   {
159     boolean stateChanged = running.compareAndSet(false, true);
160     if (!stateChanged)
161       throw new RuntimeException("Consumer instance " + id + " is already running!");
162
163     log.info("{} - Starting - consumed {} messages before", id, consumed);
164     future = executor.submit(this);
165   }
166
167   public synchronized void stop() throws ExecutionException, InterruptedException
168   {
169     boolean stateChanged = running.compareAndSet(true, false);
170     if (!stateChanged)
171       throw new RuntimeException("Consumer instance " + id + " is not running!");
172
173     log.info("{} - Stopping", id);
174     consumer.wakeup();
175     future.get();
176     log.info("{} - Stopped - consumed {} messages so far", id, consumed);
177   }
178
179   @PreDestroy
180   public void destroy() throws ExecutionException, InterruptedException
181   {
182     log.info("{} - Destroy!", id);
183     try
184     {
185       stop();
186     }
187     catch (IllegalStateException e)
188     {
189       log.info("{} - Was already stopped", id);
190     }
191     finally
192     {
193       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
194     }
195   }
196 }