import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import java.time.Clock;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
repository,
properties.getClientId(),
properties.getTopic(),
+ Clock.systemDefaultZone(),
+ properties.getCommitInterval(),
kafkaConsumer,
handler);
}
import org.apache.kafka.common.errors.WakeupException;
import javax.annotation.PreDestroy;
+import java.time.Clock;
import java.time.Duration;
+import java.time.Instant;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
private final PartitionStatisticsRepository repository;
private final String id;
private final String topic;
+ private final Clock clock;
+ private final Duration commitInterval;
private final Consumer<K, V> consumer;
private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
log.info("{} - Subscribing to topic {}", id, topic);
consumer.subscribe(Arrays.asList(topic), this);
+ Instant lastCommit = clock.instant();
+
while (true)
{
ConsumerRecords<K, V> records =
byKey.put(key, seenByKey);
}
- seen.forEach((partiton, statistics) -> repository.save(
- new StatisticsDocument(
- partiton,
- statistics,
- consumer.position(new TopicPartition(topic, partiton)))));
+ if (lastCommit.plus(commitInterval).isBefore(clock.instant()))
+ {
+ log.debug("Storing data and offsets, last commit: {}", lastCommit);
+ seen.forEach((partiton, statistics) -> repository.save(
+ new StatisticsDocument(
+ partiton,
+ statistics,
+ consumer.position(new TopicPartition(topic, partiton)))));
+ lastCommit = clock.instant();
+ }
}
}
catch(WakeupException e)
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
+import java.time.Clock;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ExecutionException;
properties = {
"consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
"consumer.topic=" + TOPIC,
+ "consumer.commit-interval=1s",
"spring.mongodb.embedded.version=4.4.13" })
@EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
@EnableAutoConfiguration
repository,
properties.getClientId(),
properties.getTopic(),
+ Clock.systemDefaultZone(),
+ properties.getCommitInterval(),
kafkaConsumer,
captureOffsetAndExecuteTestHandler);