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