kfkPyConsumerPy001.py 1.43 KB
from pykafka import KafkaClient
from pykafka.common import OffsetType

# Kafka 代理地址
kafka_broker = '192.168.3.131:9092'  # 例如:'localhost:9092'

# Kafka 主题名称
kafka_topic = 'my_test_topic'

# 消费者组
consumer_group = 'wx_testgro_005'

# ZooKeeper 服务器地址
zookeeper_address = '192.168.3.131:2181'  # 例如:'localhost:2181'

# 创建 Kafka 客户端
client = KafkaClient(hosts=kafka_broker)

# 创建 Kafka 消费者
topic = client.topics[kafka_topic.encode('utf-8')]
consumer = topic.get_balanced_consumer(
    consumer_group=consumer_group.encode('utf-8'),
    auto_commit_enable=False,
    zookeeper_connect=zookeeper_address
)

# 从 ZooKeeper 获取偏移量并设置消费者的起始偏移量
for partition in consumer._partitions.values():
    offset_path = f'/consumers/{consumer_group}/{kafka_topic}/{partition._partition_id}'
    offset = client.zk.get(offset_path)[0].decode('utf-8')
    partition.reset_offset(OffsetType.EARLIEST if offset == '-1' else int(offset))

# 消费消息
for message in consumer:
    if message is not None:
        print(f"Received message: {message.value.decode('utf-8')}")

        # 获取消息的分区和偏移量
        partition_id = message.partition.id
        offset = message.offset

        # 将偏移量保存回 ZooKeeper
        offset_path = f'/consumers/{consumer_group}/{kafka_topic}/{partition_id}'
        client.zk.set(offset_path, str(offset).encode('utf-8'))