Rückbau auf verschachtelte Maps
[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 ->
78           {
79             log.info("{} - removing partition: {}", id, tp);
80             Map<String, Integer> removed = seen.remove(tp.partition());
81             for (String key : removed.keySet())
82             {
83               log.info(
84                   "{} - Seen {} messages for partition={}|key={}",
85                   id,
86                   removed.get(key),
87                   tp.partition(),
88                   key);
89             }
90           });
91         }
92
93         @Override
94         public void onPartitionsAssigned(Collection<TopicPartition> partitions)
95         {
96           partitions.forEach(tp ->
97           {
98             log.info("{} - adding partition: {}", id, tp);
99             seen.put(tp.partition(), new HashMap<>());
100           });
101         }
102       });
103
104       while (true)
105       {
106         ConsumerRecords<String, String> records =
107             consumer.poll(Duration.ofSeconds(1));
108
109         // Do something with the data...
110         log.info("{} - Received {} messages", id, records.count());
111         for (ConsumerRecord<String, String> record : records)
112         {
113           consumed++;
114           log.info(
115               "{} - {}: {}/{} - {}={}",
116               id,
117               record.offset(),
118               record.topic(),
119               record.partition(),
120               record.key(),
121               record.value()
122           );
123
124           Integer partition = record.partition();
125           String key = record.key() == null ? "NULL" : record.key();
126           Map<String, Integer> byKey = seen.get(partition);
127
128           if (!byKey.containsKey(key))
129             byKey.put(key, 0);
130
131           int seenByKey = byKey.get(key);
132           seenByKey++;
133           byKey.put(key, seenByKey);
134         }
135       }
136     }
137     catch(WakeupException e)
138     {
139       log.info("{} - RIIING!", id);
140     }
141     catch(Exception e)
142     {
143       log.error("{} - Unexpected error: {}", id, e.toString(), e);
144       running.set(false); // Mark the instance as not running
145     }
146     finally
147     {
148       log.info("{} - Closing the KafkaConsumer", id);
149       consumer.close();
150       log.info("{} - Consumer-Thread exiting", id);
151     }
152   }
153
154   public Map<Integer, Map<String, Integer>> getSeen()
155   {
156     return seen;
157   }
158
159   public synchronized void start()
160   {
161     boolean stateChanged = running.compareAndSet(false, true);
162     if (!stateChanged)
163       throw new RuntimeException("Consumer instance " + id + " is already running!");
164
165     log.info("{} - Starting - consumed {} messages before", id, consumed);
166     future = executor.submit(this);
167   }
168
169   public synchronized void stop() throws ExecutionException, InterruptedException
170   {
171     boolean stateChanged = running.compareAndSet(true, false);
172     if (!stateChanged)
173       throw new RuntimeException("Consumer instance " + id + " is not running!");
174
175     log.info("{} - Stopping", id);
176     consumer.wakeup();
177     future.get();
178     log.info("{} - Stopped - consumed {} messages so far", id, consumed);
179   }
180
181   @PreDestroy
182   public void destroy() throws ExecutionException, InterruptedException
183   {
184     log.info("{} - Destroy!", id);
185     try
186     {
187       stop();
188     }
189     catch (IllegalStateException e)
190     {
191       log.info("{} - Was already stopped", id);
192     }
193     finally
194     {
195       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
196     }
197   }
198 }