kfkPyConsumerZoo1.py
1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from kafka import KafkaConsumer, TopicPartition
from kazoo.client import KazooClient
# 配置 ZooKeeper 和 Kafka 信息
zookeeper_address = '192.168.3.131:2181'
kafka_topic = 'my_test_topic'
kafka_consumer_group = 'wx_testgro_001'
bootstrap_servers_address = '192.168.3.131:9092'
# 创建 ZooKeeper 客户端
zk = KazooClient(hosts=zookeeper_address)
zk.start()
# 创建 Kafka 消费者
consumer = KafkaConsumer(
kafka_topic,
group_id=kafka_consumer_group,
enable_auto_commit=False, # 禁用自动提交偏移量
auto_offset_reset='earliest', # 设置偏移量起始点
bootstrap_servers=bootstrap_servers_address, # 替换为您的 Kafka 代理地址
)
# 获取 ZooKeeper 中的偏移量
partitions = consumer.partitions_for_topic(kafka_topic)
for partition in partitions:
path = f"/consumers/{kafka_consumer_group}/offsets/{kafka_topic}/{partition}"
offset, _ = zk.get(path)
if offset is not None:
offset = int(offset.decode('utf-8'))
consumer.seek(TopicPartition(kafka_topic, partition), offset)
# 消费消息
for message in consumer:
print(f"Received message: {message.value.decode('utf-8')}")
# 在处理消息后手动提交偏移量
consumer.commit()
# 关闭 Kafka 消费者和 ZooKeeper 连接
consumer.close()
zk.stop()
zk.close()