使用时间戳来消费消息(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)
相关推荐
郝学胜-神的一滴1 天前
Effective Python 第52条:用subprocess模块优雅管理子进程
linux·服务器·开发语言·python
万粉变现经纪人1 天前
如何解决 pip install 编译报错 ‘cl.exe’ not found(缺少 VS C++ 工具集)问题
开发语言·c++·人工智能·python·pycharm·bug·pip
r***11331 天前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
___波子 Pro Max.1 天前
Python类型注解详解与应用
python
1***Q7841 天前
Python增强现实案例
开发语言·python·ar
Q26433650231 天前
【有源码】spark与hadoop-情感挖掘+画像建模的携程酒店评价数据分析可视化系统-基于机器学习的携程酒店评价情感分析与竞争态势可视化
大数据·hadoop·python·机器学习·数据分析·spark·毕业设计
倚肆1 天前
Spring Boot 中的 Bean 与自动装配详解
spring boot·后端·python
不剪发的Tony老师1 天前
PyScripter:一款免费开源、功能强大的Python开发工具
ide·python
FL171713141 天前
Pytorch保存pt和pkl
人工智能·pytorch·python
爱学习的小道长1 天前
进程、线程、协程三者的区别和联系
python·ubuntu