Merge branch 'rebalance-listener' into stored-state
[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 PartitionStatisticsRepository repository;
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 final Map<Integer, Map<String, Integer>> seen = new HashMap<>();
38
39
40   public EndlessConsumer(
41       ExecutorService executor,
42       PartitionStatisticsRepository repository,
43       String bootstrapServer,
44       String groupId,
45       String clientId,
46       String topic,
47       String autoOffsetReset)
48   {
49     this.executor = executor;
50     this.repository = repository;
51     this.bootstrapServer = bootstrapServer;
52     this.groupId = groupId;
53     this.id = clientId;
54     this.topic = topic;
55     this.autoOffsetReset = autoOffsetReset;
56   }
57
58   @Override
59   public void run()
60   {
61     try
62     {
63       Properties props = new Properties();
64       props.put("bootstrap.servers", bootstrapServer);
65       props.put("group.id", groupId);
66       props.put("client.id", id);
67       props.put("auto.offset.reset", autoOffsetReset);
68       props.put("metadata.max.age.ms", "1000");
69       props.put("key.deserializer", StringDeserializer.class.getName());
70       props.put("value.deserializer", StringDeserializer.class.getName());
71
72       this.consumer = new KafkaConsumer<>(props);
73
74       log.info("{} - Subscribing to topic {}", id, topic);
75       consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
76       {
77         @Override
78         public void onPartitionsRevoked(Collection<TopicPartition> partitions)
79         {
80           partitions.forEach(tp ->
81           {
82             log.info("{} - removing partition: {}", id, tp);
83             Map<String, Integer> removed = seen.remove(tp.partition());
84             for (String key : removed.keySet())
85             {
86               log.info(
87                   "{} - Seen {} messages for partition={}|key={}",
88                   id,
89                   removed.get(key),
90                   tp.partition(),
91                   key);
92             }
93             repository.save(new StatisticsDocument(tp.partition(), removed));
94           });
95         }
96
97         @Override
98         public void onPartitionsAssigned(Collection<TopicPartition> partitions)
99         {
100           partitions.forEach(tp ->
101           {
102             log.info("{} - adding partition: {}", id, tp);
103             seen.put(
104                 tp.partition(),
105                 repository
106                     .findById(Integer.toString(tp.partition()))
107                     .map(document -> document.statistics)
108                     .orElse(new HashMap<>()));
109           });
110         }
111       });
112
113       while (true)
114       {
115         ConsumerRecords<String, String> records =
116             consumer.poll(Duration.ofSeconds(1));
117
118         // Do something with the data...
119         log.info("{} - Received {} messages", id, records.count());
120         for (ConsumerRecord<String, String> record : records)
121         {
122           consumed++;
123           log.info(
124               "{} - {}: {}/{} - {}={}",
125               id,
126               record.offset(),
127               record.topic(),
128               record.partition(),
129               record.key(),
130               record.value()
131           );
132
133           Integer partition = record.partition();
134           String key = record.key() == null ? "NULL" : record.key();
135           Map<String, Integer> byKey = seen.get(partition);
136
137           if (!byKey.containsKey(key))
138             byKey.put(key, 0);
139
140           int seenByKey = byKey.get(key);
141           seenByKey++;
142           byKey.put(key, seenByKey);
143         }
144       }
145     }
146     catch(WakeupException e)
147     {
148       log.info("{} - RIIING!", id);
149     }
150     catch(Exception e)
151     {
152       log.error("{} - Unexpected error: {}", id, e.toString(), e);
153       running.set(false); // Mark the instance as not running
154     }
155     finally
156     {
157       log.info("{} - Closing the KafkaConsumer", id);
158       consumer.close();
159       log.info("{} - Consumer-Thread exiting", id);
160     }
161   }
162
163   public Map<Integer, Map<String, Integer>> getSeen()
164   {
165     return seen;
166   }
167
168   public synchronized void start()
169   {
170     boolean stateChanged = running.compareAndSet(false, true);
171     if (!stateChanged)
172       throw new RuntimeException("Consumer instance " + id + " is already running!");
173
174     log.info("{} - Starting - consumed {} messages before", id, consumed);
175     future = executor.submit(this);
176   }
177
178   public synchronized void stop() throws ExecutionException, InterruptedException
179   {
180     boolean stateChanged = running.compareAndSet(true, false);
181     if (!stateChanged)
182       throw new RuntimeException("Consumer instance " + id + " is not running!");
183
184     log.info("{} - Stopping", id);
185     consumer.wakeup();
186     future.get();
187     log.info("{} - Stopped - consumed {} messages so far", id, consumed);
188   }
189
190   @PreDestroy
191   public void destroy() throws ExecutionException, InterruptedException
192   {
193     log.info("{} - Destroy!", id);
194     try
195     {
196       stop();
197     }
198     catch (IllegalStateException e)
199     {
200       log.info("{} - Was already stopped", id);
201     }
202     finally
203     {
204       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
205     }
206   }
207 }