Offset-Position wird in der MongoDB gespeichert
[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<TopicPartition, PartitionStatistics> 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("enable.auto.commit", false);
68       props.put("auto.offset.reset", autoOffsetReset);
69       props.put("metadata.max.age.ms", "1000");
70       props.put("key.deserializer", StringDeserializer.class.getName());
71       props.put("value.deserializer", StringDeserializer.class.getName());
72
73       this.consumer = new KafkaConsumer<>(props);
74
75       log.info("{} - Subscribing to topic {}", id, topic);
76       consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
77       {
78         @Override
79         public void onPartitionsRevoked(Collection<TopicPartition> partitions)
80         {
81           partitions.forEach(tp ->
82           {
83             log.info("{} - removing partition: {}", id, tp);
84             PartitionStatistics removed = seen.remove(tp);
85             for (KeyCounter counter : removed.getStatistics())
86             {
87               log.info(
88                   "{} - Seen {} messages for partition={}|key={}",
89                   id,
90                   counter.getResult(),
91                   removed.getPartition(),
92                   counter.getKey());
93             }
94             repository.save(new StatisticsDocument(removed, consumer.position(tp)));
95           });
96         }
97
98         @Override
99         public void onPartitionsAssigned(Collection<TopicPartition> partitions)
100         {
101           partitions.forEach(tp ->
102           {
103             log.info("{} - adding partition: {}", id, tp);
104             StatisticsDocument document =
105                 repository
106                     .findById(tp.toString())
107                     .orElse(new StatisticsDocument(tp));
108             consumer.seek(tp, document.offset);
109             seen.put(tp, new PartitionStatistics(document));
110           });
111         }
112       });
113
114       while (true)
115       {
116         ConsumerRecords<String, String> records =
117             consumer.poll(Duration.ofSeconds(1));
118
119         // Do something with the data...
120         log.info("{} - Received {} messages", id, records.count());
121         for (ConsumerRecord<String, String> record : records)
122         {
123           consumed++;
124           log.info(
125               "{} - {}: {}/{} - {}={}",
126               id,
127               record.offset(),
128               record.topic(),
129               record.partition(),
130               record.key(),
131               record.value()
132           );
133
134           TopicPartition partition = new TopicPartition(record.topic(), record.partition());
135           String key = record.key() == null ? "NULL" : record.key();
136           seen.get(partition).increment(key);
137         }
138       }
139     }
140     catch(WakeupException e)
141     {
142       log.info("{} - RIIING!", id);
143     }
144     catch(Exception e)
145     {
146       log.error("{} - Unexpected error: {}", id, e.toString(), e);
147       running.set(false); // Mark the instance as not running
148     }
149     finally
150     {
151       log.info("{} - Closing the KafkaConsumer", id);
152       consumer.close();
153       log.info("{} - Consumer-Thread exiting", id);
154     }
155   }
156
157   public Map<TopicPartition, PartitionStatistics> getSeen()
158   {
159     return seen;
160   }
161
162   public synchronized void start()
163   {
164     boolean stateChanged = running.compareAndSet(false, true);
165     if (!stateChanged)
166       throw new RuntimeException("Consumer instance " + id + " is already running!");
167
168     log.info("{} - Starting - consumed {} messages before", id, consumed);
169     future = executor.submit(this);
170   }
171
172   public synchronized void stop() throws ExecutionException, InterruptedException
173   {
174     boolean stateChanged = running.compareAndSet(true, false);
175     if (!stateChanged)
176       throw new RuntimeException("Consumer instance " + id + " is not running!");
177
178     log.info("{} - Stopping", id);
179     consumer.wakeup();
180     future.get();
181     log.info("{} - Stopped - consumed {} messages so far", id, consumed);
182   }
183
184   @PreDestroy
185   public void destroy() throws ExecutionException, InterruptedException
186   {
187     log.info("{} - Destroy!", id);
188     try
189     {
190       stop();
191     }
192     catch (IllegalStateException e)
193     {
194       log.info("{} - Was already stopped", id);
195     }
196     finally
197     {
198       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
199     }
200   }
201 }