Article
kafka 获取时间戳所在时间的偏移量
这是 kafka获取时间戳所在时间的偏移量 的小白文,哈,类似的这种骚操作很容易忘记,所以记录下。
当生产环境遇到问题的时候,我们需要从某时间段开始消费消息补充数据,类似于旁路脚本进行数据修复,这时候我们如果知道出问题的时间点,然后从当前时间点进行消费数据就很完美了。
我们都知道直接编写代码可以直接定位到时间点所在的位置,但是基本原理都是获取该时间戳的所有分区的偏移量,然后从该偏移量开始取数据。
既然知道了原理,那怎么从指定时间戳取到所有分区的偏移量?
kafka提供了直接的命令工具来获取指定时间戳的所有分区偏移量,跟自己编写代码是类似的。
命令:
./kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list 127.0.0.1:9092 --topic opxxxPostTopic --time 1583808808000
获取topic为 opxxxPostTopic 的所有分区在 1583808808000 这个时间点的偏移量。
执行结果为:
// topic名称:分区序号:偏移量
opxxxPostTopic:0:7022
opxxxPostTopic:1:6897
opxxxPostTopic:2:7019
opxxxPostTopic:3:7018
opxxxPostTopic:4:6901
opxxxPostTopic:5:7009
opxxxPostTopic:6:7011
opxxxPostTopic:7:6894
opxxxPostTopic:8:7003
opxxxPostTopic:9:7011
opxxxPostTopic:10:6892
opxxxPostTopic:11:7016
opxxxPostTopic:12:7021
其中 ./kafka-run-class.sh kafka.tools.GetOffsetShell 这个命令的解释如下,可以自己操作试下。
./kafka-run-class.sh kafka.tools.GetOffsetShell
[xxx@sit2kafka148vl:/xxx/kafka-env/bin]$./kafka-run-class.sh kafka.tools.GetOffsetShell
An interactive shell for getting topic offsets.
Option Description
------ -----------
--broker-list <String: hostname: REQUIRED: The list of hostname and
port,...,hostname:port> port of the server to connect to.
--max-wait-ms <Integer: ms> DEPRECATED AND IGNORED: The max amount
of time each fetch request waits.
(default: 1000)
--offsets <Integer: count> DEPRECATED AND IGNORED: number of
offsets returned (default: 1)
--partitions <String: partition ids> comma separated list of partition ids.
If not specified, it will find
offsets for all partitions (default:
)
--time <Long: timestamp/-1(latest)/-2 timestamp of the offsets before that.
(earliest)> [Note: No offset is returned, if the
timestamp greater than recently
commited record timestamp is given.]
(default: -1)
--topic <String: topic> REQUIRED: The topic to get offset from.
可以看到 --time 就是设置时间点。
一开始我搜索了下有没有人讲解过这种基本操作,然而看到的都是各种拷贝粘贴的文章,各种扯淡,还是官方文档看着舒服,可惜的就是访问起来太慢了,打开一个kafka工具文档页面耗时将近10分钟,天朝的墙啊。。。