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

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

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

请注意,时间戳是以毫秒为单位的UNIX时间戳。需要根据需要调整start_timestampend_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)
相关推荐
满怀冰雪2 小时前
06-自动微分入门:用 Paddle 计算梯度
人工智能·python·深度学习·paddle
xlrqx8 小时前
家电清洗培训课程类别、培训方式及费用情况究竟有哪些
大数据·python
lbb 小魔仙8 小时前
VS Code Python 高级调试技巧:从入门到精通
开发语言·python
lzqrzpt8 小时前
LED驱动电源行业品牌格局与技术差异深度总结
python·单片机·嵌入式硬件
李可以量化8 小时前
PTrade 策略入门:before_trading_start 函数详解(上)—— 盘前准备逻辑全指南
python
大海变好AI8 小时前
AIGC分层推理落地能否串联多工具完成自动化闭环
人工智能·python·自动化·aigc
二宝哥9 小时前
14.Python模块与包完全指南:从定义到实战
python
三声三视9 小时前
交互式用够了?用 Agent SDK 把 Claude 塞进 Python Web 服务
人工智能·python·ai·aigc·ai编程
zhanghaha131410 小时前
Python语言基础:4_数据类型转换
java·前端·python
海棠Flower未眠10 小时前
SpringBoot 整合 Kafka 高性能消息队列(荣耀典藏版)
分布式·kafka