使用时间戳来消费消息(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)
相关推荐
Y学院11 小时前
Python 数据分析:从新手到高手的“摸鱼”指南
python·数据分析
free11 小时前
基于librdkafa C++客户端生产者发送数据失败问题处理#2
c++·kafka
不吃饭的猪11 小时前
kafka启动小脚本
分布式·kafka
深耕AI11 小时前
【PyTorch训练】准确率计算(代码片段拆解)
人工智能·pytorch·python
eqwaak011 小时前
科技信息差(9.12)
开发语言·python·科技·量子计算
Blossom.11812 小时前
从“能写”到“能干活”:大模型工具调用(Function-Calling)的工程化落地指南
数据库·人工智能·python·深度学习·机器学习·计算机视觉·oracle
蒋星熠12 小时前
破壁者指南:内网穿透技术的深度解构与实战方法
网络·数据库·redis·python·websocket·网络协议·udp
shizidushu12 小时前
使用 Pyinstaller 打包 PPOCRLabel
python·pyinstaller
Q_Q196328847513 小时前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php