如果您的 Kafka 消息具有正确的时间戳,那么您可以获得前一周时间戳的偏移量。所以你可以使用..
Map<TopicPartition,OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition,Long> timestampsToSearch)
documentation 说:
按时间戳查找给定分区的偏移量。这
每个分区的返回偏移量是其最早的偏移量
时间戳大于或等于给定时间戳
对应的分区。
要获取主题分区列表,您可以调用consumer.assignment()(在subscribe() 或assign() 之后)返回分配给消费者的Set<TopicPartition>。地图中的Long 值基本上就是时间戳。因此,对于您案例中的所有键,它将是相同的值(即 1 周大的时间戳)
现在,您有一个Map<TopicPartition, OffsetAndTimestamp>。您现在可以使用seek(TopicPartition partition, long offset) 查找每个偏移量。
consumer.subscribe(topics);
Set<TopicPartition> partitions = consumer.assignment();
Map<TopicPartition, Long> map = new LinkedHashMap<>();
partitions.forEach(partition -> map.put(partition, oneWeekOldTimestamp));
Map<TopicPartition, OffsetAndTimestamp> offsetsMap = consumer.offsetForTimes(map);
offsetsMap.forEach((partition, offsetTimestamp) -> consumer.seek(partition, offsetTimestamp.offset()));
现在,您的消费者将处于一周前的消息位置。所以,当你poll() 时,你从上周到现在进行投票。
您可以更改时间戳以满足您的要求,例如,任何超过 1 周的时间都意味着,从时间戳 0 到上周时间戳。
所有前一周数据均指2weekOldTimestamp - 1weekOldTimestamp。
因此,在这种情况下,您必须寻找2weekOldTimestamp,然后处理每个分区,直到遇到1weekOldTimestamp