使用时间戳来消费消息(kafka)

每条消息都有一个与之相关的时间戳(timestamp),可以使用这个时间戳来筛选或消费特定时间范围内的消息。

timestamp()方法获取消息的时间戳,并检查它是否在指定的时间范围内。

请注意,时间戳是以毫秒为单位的UNIX时间戳。需要根据需要调整start_timestamp和end_timestamp的值。

python 复制代码
from confluent_kafka import Consumer, KafkaError

def consume_messages_by_timestamp(bootstrap_servers, group_id, topic, start_timestamp, end_timestamp):
    consumer_config = {
        'bootstrap.servers': bootstrap_servers,
        'group.id': group_id,
        'auto.offset.reset': 'earliest',  # 从最早的偏移量开始消费
    }

    consumer = Consumer(consumer_config)

    # 订阅主题
    consumer.subscribe([topic])

    try:
        while True:
            msg = consumer.poll(1.0)  # 1秒的超时时间

            if msg is None:
                continue

            if msg.error():
                if msg.error().code() == KafkaError._PARTITION_EOF:
                    # 到达分区末尾,继续等待消息
                    continue
                else:
                    print(f"消费者错误: {msg.error()}")
                    break

            # 获取消息的时间戳
            timestamp = msg.timestamp()[1]

            # 检查消息是否在指定的时间范围内
            if start_timestamp <= timestamp <= end_timestamp:
                print(f"从主题 '{msg.topic()}' 的分区 '{msg.partition()}' 接收到消息: {msg.value().decode('utf-8')}")

    except KeyboardInterrupt:
        pass

    finally:
        # 关闭消费者
        consumer.close()

# 示例用法
bootstrap_servers = 'your_kafka_bootstrap_servers'
group_id = 'your_consumer_group_id'
topic = 'your_kafka_topic'
start_timestamp = 1642656000000  # 2022-01-20 00:00:00 in milliseconds
end_timestamp = 1642742399000    # 2022-01-20 23:59:59 in milliseconds

consume_messages_by_timestamp(bootstrap_servers, group_id, topic, start_timestamp, end_timestamp)
相关推荐
起个名字费劲死了42 分钟前
Halcon学习一:骰子识别
前端·python·学习
eric-sjq2 小时前
小思框架 · 30M 级长上下文新架构对比技术报告
人工智能·python·深度学习·语言模型
reasonsummer3 小时前
【办公类-04-05】20261030整理手机照片(华为手机助手导出照片到日期文件夹+批量添加四级文件夹+手动转移照片更名+更改三级文件夹合并汉字名称)
python·智能手机
BD_Marathon4 小时前
【Python】初识迭代器
python
gz927cool4 小时前
Python 全栈应用最佳实践完整指南
开发语言·python·ai
智购科技智能售货柜4 小时前
顾客已经关门,视觉售货柜还在处理旧画面:延迟积压怎么查?~YH
python·单片机·嵌入式硬件·物联网·eclipse
梯度下降者4 小时前
Python从0到100(三):Python中的变量介绍
python·作用域·变量·数据类型·计算机常识
AIFQuant4 小时前
Python期货行情API接入:股指、黄金、原油多品种数据管道实战
开发语言·python·金融·区块链·量化开发
一条泥憨鱼5 小时前
【Kafka】零基础学习教程
java·分布式·学习·kafka
威哥爱编程5 小时前
Python 智能体开发实战 07:让它查课表它张口就编?给 Agent 接上真正能动手的工具
python·agent