使用时间戳来消费消息(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)
相关推荐
财经资讯数据_灵砚智能14 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月2日
人工智能·python·信息可视化·自然语言处理·ai编程
skiy19 分钟前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
2601_9561394221 分钟前
集团品牌全案公司哪家专业
大数据·人工智能·python
ouliten21 分钟前
[Triton笔记1]核心概念
笔记·python·深度学习·triton
清水白石00822 分钟前
生成器不是性能银弹:什么时候该用 `yield` 省内存,什么时候它会拖慢 Python 数据处理吞吐?
开发语言·python·原型模式
李松桃23 分钟前
Python爬虫-实战
爬虫·python
观无31 分钟前
Python读取excel并形成api接口案例
python·pandas·fastapi
alwaysrun36 分钟前
Python之文档自动上传至飞书云盘
python·飞书·uploader·云盘
如何原谅奋力过但无声38 分钟前
【灵神高频面试题合集04-05】二分查找
数据结构·python·算法·leetcode
财经资讯数据_灵砚智能40 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年5月3日
大数据·人工智能·python·信息可视化·自然语言处理