LoginSignup
1
2

More than 5 years have passed since last update.

pythonでkafka consumerで最初のoffsetからメッセージを取得する

Posted at
背景

kafkaにリアルタイムデータを入れてるけど、offsetの最初からデータを取得したくなった。
その方法がドキュメントに書かれてないので、備忘録として書いておく

ライブラリ

いくつかkafkaのライブラリがあるようだけど
kafka-python 1.3.2を使うことにする

コード
from kafka import KafkaConsumer, TopicPartition
consumer = KafkaConsumer(bootstrap_servers='hoge')

tp = TopicPartition('topic_name', 0)
consumer.assign([tp])
consumer.seek(tp, 0)

for msg in consumer:
    // do something
説明

KafkaConsumerのコンストラクタでトピックを指定せずにTopicPartitionをつかってトピック名を指定する。
あとはseekでTopicPartitionとoffsetを指定してあげるとできる

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2