kfkPyConsumerZoo2.py 1.68 KB
from kafka import KafkaConsumer
from kazoo.client import KazooClient
import json

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

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

# Kafka 主题名称
kafka_topic = 'my_test_topic'

# 消费者组
consumer_group = 'wx_testgro_002'

# 创建 ZooKeeper 客户端
zk = KazooClient(hosts=zookeeper_address)
zk.start()

# 创建 Kafka 消费者
consumer = KafkaConsumer(
    kafka_topic,
    group_id=consumer_group,
    bootstrap_servers=kafka_broker,
    enable_auto_commit=False  # 禁用自动提交偏移量
)

# 获取或创建 ZooKeeper 节点来存储 offset
offset_node = f'/kafka-offsets/{kafka_topic}/{consumer_group}'

if not zk.exists(offset_node):
    # 如果节点不存在,创建一个初始 offset
    zk.create(offset_node, json.dumps({'offset': 0}).encode('utf-8'))

# 从 ZooKeeper 获取 offset
offset, _ = zk.get(offset_node)
offset = json.loads(offset.decode('utf-8'))['offset']

# 设置 Kafka 消费者的起始偏移量
consumer.seek_to_end()
end_offset = consumer.position(TopicPartition(kafka_topic, 0))
if offset >= end_offset:
    offset = end_offset - 1  # 如果 offset 大于或等于末尾偏移量,将其设置为末尾偏移量的前一个位置
consumer.seek(TopicPartition(kafka_topic, 0), offset)

# 消费消息
for message in consumer:
    print(f"Received message: {message.value.decode('utf-8')}")
    
    # 处理消息后,保存偏移量到 ZooKeeper
    offset = message.offset
    zk.set(offset_node, json.dumps({'offset': offset}).encode('utf-8'))

# 关闭 ZooKeeper 客户端和 Kafka 消费者
zk.stop()
zk.close()
consumer.close()