kfkPyConsumerZoo3.py
2.06 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from kafka import KafkaConsumer
from kafka.common import TopicPartition
from kazoo.client import KazooClient
# Kafka 代理地址
kafka_broker = '192.168.3.131:9092' # 例如:'localhost:9092'
# Kafka 主题名称
kafka_topic = 'my_test_topic'
# 消费者组
consumer_group = 'wx_testgro_003'
# ZooKeeper 服务器地址
zookeeper_address = '192.168.3.131:2181' # 例如:'localhost:2181'
# 创建 Kafka 消费者
consumer = KafkaConsumer(
kafka_topic,
group_id=consumer_group,
bootstrap_servers=kafka_broker,
enable_auto_commit=False # 禁用自动提交偏移量
)
# 连接到 ZooKeeper
zk = KazooClient(hosts=zookeeper_address)
zk.start()
print('zookeeper init succ')
# 创建 ZooKeeper 消费者路径
consumer_path = f'/consumers/{consumer_group}'
if not zk.exists(consumer_path):
zk.create(consumer_path, b'', makepath=True)
print('zookeeper path init')
# 获取分区列表
partitions = consumer.partitions_for_topic(kafka_topic)
print('zookeeper partitions getting')
# 获取和设置偏移量
for partition in partitions:
offset_path = f'{consumer_path}/{kafka_topic}/{partition}'
if zk.exists(offset_path):
# 如果偏移量已存在,获取偏移量并设置 Kafka 消费者的起始偏移量
offset, _ = zk.get(offset_path)
offset = int(offset)
consumer.seek(TopicPartition(kafka_topic, partition), offset)
print('exists offset value:%s', partition, offset)
else:
# 如果偏移量不存在,将其设置为 0
zk.create(offset_path, b'0', makepath=True)
print('zookeeper partitions getted')
# 消费消息
for message in consumer:
print(f"Received message: {message.value.decode('utf-8')}")
# 获取消息的分区和偏移量
partition = message.partition
offset = message.offset
# 将偏移量保存回 ZooKeeper
offset_path = f'{consumer_path}/{kafka_topic}/{partition}'
zk.set(offset_path, str(offset).encode('utf-8'))
print('consumer cloesing')
# 关闭 Kafka 消费者和 ZooKeeper 连接
consumer.close()
zk.stop()
zk.close()
print('consumer cloesed')