Thread-Synchronisation bei start/stop überarbeitet
[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.Properties;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.locks.Condition;
17 import java.util.concurrent.locks.Lock;
18 import java.util.concurrent.locks.ReentrantLock;
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 final Lock lock = new ReentrantLock();
32   private final Condition condition = lock.newCondition();
33   private boolean running = false;
34   private long consumed = 0;
35   private KafkaConsumer<String, String> consumer = null;
36
37
38   public EndlessConsumer(
39       ExecutorService executor,
40       String bootstrapServer,
41       String groupId,
42       String clientId,
43       String topic,
44       String autoOffsetReset)
45   {
46     this.executor = executor;
47     this.bootstrapServer = bootstrapServer;
48     this.groupId = groupId;
49     this.id = clientId;
50     this.topic = topic;
51     this.autoOffsetReset = autoOffsetReset;
52   }
53
54   @Override
55   public void run()
56   {
57     try
58     {
59       Properties props = new Properties();
60       props.put("bootstrap.servers", bootstrapServer);
61       props.put("group.id", groupId);
62       props.put("client.id", id);
63       props.put("auto.offset.reset", autoOffsetReset);
64       props.put("key.deserializer", StringDeserializer.class.getName());
65       props.put("value.deserializer", StringDeserializer.class.getName());
66
67       this.consumer = new KafkaConsumer<>(props);
68
69       log.info("{} - Subscribing to topic {}", id, topic);
70       consumer.subscribe(Arrays.asList(topic));
71
72       while (true)
73       {
74         ConsumerRecords<String, String> records =
75             consumer.poll(Duration.ofSeconds(1));
76
77         // Do something with the data...
78         log.info("{} - Received {} messages", id, records.count());
79         for (ConsumerRecord<String, String> record : records)
80         {
81           consumed++;
82           log.info(
83               "{} - {}: {}/{} - {}={}",
84               id,
85               record.offset(),
86               record.topic(),
87               record.partition(),
88               record.key(),
89               record.value()
90           );
91         }
92       }
93     }
94     catch(WakeupException e)
95     {
96       log.info("{} - RIIING!", id);
97       shutdown();
98     }
99     catch(Exception e)
100     {
101       log.error("{} - Unexpected error: {}", id, e.toString(), e);
102       shutdown();
103     }
104     finally
105     {
106       log.info("{} - Closing the KafkaConsumer", id);
107       consumer.close();
108       log.info("{} - Consumer-Thread exiting", id);
109     }
110   }
111
112   private void shutdown()
113   {
114     lock.lock();
115     try
116     {
117       running = false;
118       condition.signal();
119     }
120     finally
121     {
122       lock.unlock();
123     }
124   }
125
126   public void start()
127   {
128     lock.lock();
129     try
130     {
131       if (running)
132         throw new IllegalStateException("Consumer instance " + id + " is already running!");
133
134       log.info("{} - Starting - consumed {} messages before", id, consumed);
135       running = true;
136       executor.submit(this);
137     }
138     finally
139     {
140       lock.unlock();
141     }
142   }
143
144   public synchronized void stop() throws ExecutionException, InterruptedException
145   {
146     lock.lock();
147     try
148     {
149       if (!running)
150         throw new IllegalStateException("Consumer instance " + id + " is not running!");
151
152       log.info("{} - Stopping", id);
153       consumer.wakeup();
154       condition.await();
155       log.info("{} - Stopped - consumed {} messages so far", id, consumed);
156     }
157     finally
158     {
159       lock.unlock();
160     }
161   }
162
163   @PreDestroy
164   public void destroy() throws ExecutionException, InterruptedException
165   {
166     log.info("{} - Destroy!", id);
167     try
168     {
169       stop();
170     }
171     catch (IllegalStateException e)
172     {
173       log.info("{} - Was already stopped", id);
174     }
175     catch (Exception e)
176     {
177       log.error("{} - Unexpected exception while trying to stop the consumer", id, e);
178     }
179     finally
180     {
181       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
182     }
183   }
184 }