使用时间戳来消费消息(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)
相关推荐
宿州派大星19 分钟前
Python 音视频处理流水线:视频分离音频 + 讯飞转写 + 星火大模型解析(附完整代码与踩坑指南)
开发语言·python·音视频
I Am a robert girl42 分钟前
DiffRAC:当视频“呼吸”有了节拍器——重复动作计数的新范式
python·深度学习·计算机视觉·视频分析·视频扩散模型·重复动作计数
郝学胜-神的一滴1 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
有个傻瓜2 小时前
容器里时间凭空差 8 小时:naive 与 aware 时区混用排错复盘与四种方案实测
python·docker·springboot·时区排错·naive/aware
心流剑2 小时前
从零打造带降级路由的 Agentic RAG 校园智能体(附前端终端UI实战)
python·ai·rag
天远数科3 小时前
零信任架构实战:基于天远车辆过户详版查询构建自动化抵押车权属合规审查网关
人工智能·python·架构·自动化
badhope3 小时前
3 个 Agent 并行发文章:我用 SQLite 任务表止住重复
后端·python·ai编程
战6174 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
databook4 小时前
马尔可夫链入门:状态、转移概率与无记忆性
python·机器学习·数据分析
郝学胜-神的一滴4 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy