使用时间戳来消费消息(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)
相关推荐
三金1213815 分钟前
Python的一些内置模块
python
NPE~35 分钟前
RAG 实战教程:从零构建企业智能问答 Agent
python·ai·实战·rag·agent搭建
BaoshengTT1 小时前
2026年双流区汽车贴膜种类及挑选要点保圣威固7V不凡门店
python
zhiSiBuYu05172 小时前
Flask 请求与响应新手实战指南
后端·python·flask
宸津-代码粉碎机2 小时前
告别手动Jar部署!生产级无损热部署方案,彻底解决OOM与更新失效问题
java·大数据·开发语言·人工智能·python
米码收割机2 小时前
【移动】线上购物移动端网站(源码+文档)【独一无二】
java·开发语言·前端·python·django
未知违规用户2 小时前
大模型项目: 学习FastAPI 服务器开发
服务器·人工智能·python·学习·fastapi
想会飞的蒲公英2 小时前
PyTorch reshape、view、transpose、广播到底怎么选?
人工智能·pytorch·python
卷无止境2 小时前
Python装饰器:一层糖衣包裹的函数魔法
后端·python
xlrqx2 小时前
长治家电清洗培训基地如何挑选及行业基本培训标准科普
大数据·python