使用时间戳来消费消息(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)
相关推荐
Tbisnic12 小时前
26.AI大模型:RNN、LSTM、GRU
人工智能·python·rnn·gru·大模型·llm·lstm
七夜zippoe12 小时前
OpenClaw 实战:智能文档助手——从问答到生成的完整方案
人工智能·python·机器学习·openclaw·智能文档
卡提西亚13 小时前
leetcode-179. 最大数
python·算法
AC赳赳老秦13 小时前
时间开销自动统计:OpenClaw 记录工作任务时长、分析时间分配、给出优化建议
java·大数据·开发语言·python·自动化·deepseek·openclaw
清水白石00813 小时前
Python 类定义阶段自动注册子类:从 `__init_subclass__` 到插件系统实战
linux·前端·python
用户83562907805113 小时前
如何使用 Python 为 PDF 添加和管理图层
后端·python
祉猷并茂,雯华若锦13 小时前
Appium 3.x 实战:元素定位与常见错误解析
开发语言·python·appium
jiang_changsheng14 小时前
Conda 的默认环境创建优先级。
linux·windows·python
FriendshipT14 小时前
Ultralytics:解读C2fCIB模块
人工智能·pytorch·python·深度学习·目标检测
c_lb728814 小时前
2026年AI量化学习流程,从表达开发走到分层验证
人工智能·python