import java.time.Duration;
import java.util.Arrays;
+import java.util.concurrent.Callable;
@Slf4j
@RequiredArgsConstructor
-public class SimpleConsumer implements Runnable
+public class SimpleConsumer implements Callable<Integer>
{
private final String id;
private final String topic;
- private final Consumer<String, String> consumer;
+ private final Consumer<String, Message> consumer;
+ private final MessageHandler messageHandler;
private long consumed = 0;
@Override
- public void run()
+ public Integer call()
{
try
{
while (true)
{
- ConsumerRecords<String, String> records =
+ ConsumerRecords<String, Message> records =
consumer.poll(Duration.ofSeconds(1));
log.info("{} - Received {} messages", id, records.count());
- for (ConsumerRecord<String, String> record : records)
+ for (ConsumerRecord<String, Message> record : records)
{
- consumed++;
- log.info(
- "{} - {}: {}/{} - {}={}",
- id,
- record.offset(),
- record.topic(),
- record.partition(),
- record.key(),
- record.value()
- );
+ handleRecord(
+ record.topic(),
+ record.partition(),
+ record.offset(),
+ record.key(),
+ record.value());
}
}
}
catch(WakeupException e)
{
log.info("{} - Consumer was signaled to finish its work", id);
+ return 0;
}
catch(Exception e)
{
- log.error("{} - Unexpected error: {}, unsubscribing!", id, e.toString());
- consumer.unsubscribe();
+ log.error("{} - Unexpected error: {}!", id, e.toString());
+ return 1;
}
finally
{
log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
}
}
+
+ private void handleRecord(
+ String topic,
+ Integer partition,
+ Long offset,
+ String key,
+ Message value)
+ {
+ consumed++;
+ log.info("{} - {}: {}/{} - {}={}", id, offset, topic, partition, key, value);
+ messageHandler.handle(key, value);
+ }
}