使用时间戳来消费消息(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)
相关推荐
qq_1898070321 小时前
golang如何实现日志按级别过滤_golang日志按级别过滤实现教程
jvm·数据库·python
abc123456sdggfd21 小时前
Golang map底层实现原理_Golang map哈希表原理教程【经典】
jvm·数据库·python
yaoxin52112321 小时前
391. Java 文件操作基础 - 方法链式调用
java·开发语言·python
justjinji21 小时前
JavaScript中利用宏任务拆分阻塞任务的实操案例
jvm·数据库·python
weixin_408717771 天前
c++如何实现跨平台的文件读写进度监听器回调机制【实战】
jvm·数据库·python
一铭111991 天前
gpt-claude-gemini 超级大模型安装使用教程
java·python·gpt·ai编程·claude·gemini
2401_837163891 天前
HTML怎么标注字数限制提示_HTML实时字数统计占位【详解】
jvm·数据库·python
阿标的博客1 天前
Python学习(二):PyCharm的下载与安装
python
m0_741173331 天前
Golang Gin如何做Swagger文档_Golang Gin Swagger教程【速学】
jvm·数据库·python
AI_大白1 天前
让 Cursor 帮你搞定美股 4 个时段:AI Agent 的时段感知实战
python·架构