老版本kafka查询topic消费情况(python查询)

由于老版本的kafka缺少shell,导致无法通过命令直接进行查询,所以通过python代码,实现消费情况查询

安装必须的包

shell 复制代码
#pyhon2.5
pip install kafka-python==1.4.7

python脚本

python 复制代码
#!/usr/bin/env python
import sys
from kafka import KafkaConsumer, TopicPartition

if len(sys.argv) != 2:
    print("Usage: python queryConsumer.py <topic_name>")
    sys.exit(1)

bootstrap_servers = ['localhost:9092']

topic_name = sys.argv[1]

consumer = KafkaConsumer(
    bootstrap_servers=bootstrap_servers,
    auto_offset_reset='earliest',
    enable_auto_commit=False,
    consumer_timeout_ms=1000
)

partitions = consumer.partitions_for_topic(topic_name)
print("Partitions: ", partitions)

for partition in partitions:
    tp = TopicPartition(topic_name, partition)
    consumer.assign([tp])
    consumer.seek_to_end(tp)
    last_offset = consumer.position(tp)
    print("Partition: ", partition, "Last offset: ", last_offset)

consumer.close()

查询

复制代码
[root@vm_ tools]# python queryConsumer.py test
('Partitions: ', set([0]))
('Partition: ', 0, 'Last offset: ', 1)
相关推荐
曲幽6 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805111 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞14 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派16 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪17 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636717 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫19 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派19 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风21 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic