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;
@Override
- public void run()
+ public Integer call()
{
try
{
log.info("{} - Received {} messages", id, records.count());
for (ConsumerRecord<String, String> 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();
+ 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);
+ }
}