16
16
import lombok .extern .slf4j .Slf4j ;
17
17
import org .apache .kafka .clients .consumer .Consumer ;
18
18
import org .apache .kafka .clients .consumer .ConsumerRecords ;
19
- import org .apache .kafka .common .PartitionInfo ;
20
19
import org .apache .kafka .common .TopicPartition ;
21
20
import org .apache .kafka .common .errors .InterruptException ;
22
21
import org .hypertrace .core .serviceframework .metrics .PlatformMetricsRegistry ;
23
22
24
23
@ Slf4j
25
24
class KafkaLiveEventListenerCallable <K , V > implements Callable <Void > {
25
+
26
26
private static final String EVENT_CONSUMER_ERROR_COUNT = "event.consumer.error.count" ;
27
- private final List <TopicPartition > topicPartitions ;
28
27
private final Consumer <K , V > kafkaConsumer ;
29
28
private final Duration pollTimeout ;
30
29
private final Counter errorCounter ;
30
+ private final String topic ;
31
31
private final ConcurrentLinkedQueue <BiConsumer <? super K , ? super V >> callbacks ;
32
32
33
33
KafkaLiveEventListenerCallable (
@@ -41,16 +41,9 @@ class KafkaLiveEventListenerCallable<K, V> implements Callable<Void> {
41
41
kafkaConfig .hasPath (POLL_TIMEOUT )
42
42
? kafkaConfig .getDuration (POLL_TIMEOUT )
43
43
: Duration .ofSeconds (30 );
44
- String topic = kafkaConfig .getString (TOPIC_NAME );
44
+ this . topic = kafkaConfig .getString (TOPIC_NAME );
45
45
this .kafkaConsumer = kafkaConsumer ;
46
- // fetch partitions and seek to end of partitions to consume live events
47
- List <PartitionInfo > partitions = kafkaConsumer .partitionsFor (topic );
48
- topicPartitions =
49
- partitions .stream ()
50
- .map (p -> new TopicPartition (p .topic (), p .partition ()))
51
- .collect (Collectors .toList ());
52
- kafkaConsumer .assign (topicPartitions );
53
- kafkaConsumer .seekToEnd (topicPartitions );
46
+
54
47
this .errorCounter =
55
48
PlatformMetricsRegistry .registerCounter (
56
49
consumerName + "." + EVENT_CONSUMER_ERROR_COUNT , Collections .emptyMap ());
@@ -60,8 +53,20 @@ void addCallback(BiConsumer<? super K, ? super V> callbackFunction) {
60
53
callbacks .add (callbackFunction );
61
54
}
62
55
56
+ private List <TopicPartition > initializePartitions () {
57
+ // fetch partitions and seek to end of partitions to consume live events
58
+ List <TopicPartition > topicPartitions =
59
+ kafkaConsumer .partitionsFor (this .topic ).stream ()
60
+ .map (p -> new TopicPartition (p .topic (), p .partition ()))
61
+ .collect (Collectors .toUnmodifiableList ());
62
+ kafkaConsumer .assign (topicPartitions );
63
+ kafkaConsumer .seekToEnd (topicPartitions );
64
+ return topicPartitions ;
65
+ }
66
+
63
67
@ Override
64
68
public Void call () {
69
+ List <TopicPartition > topicPartitions = this .initializePartitions ();
65
70
do {
66
71
try {
67
72
ConsumerRecords <K , V > records = kafkaConsumer .poll (pollTimeout );
0 commit comments