kafka监控获取指定topic的消息总量示例


Posted in Python onDecember 23, 2019

我就废话不多说了,直接 上代码吧!

import kafka.api.PartitionOffsetRequestInfo;
import kafka.common.TopicAndPartition;
import kafka.javaapi.OffsetResponse;
import kafka.javaapi.PartitionMetadata;
import kafka.javaapi.TopicMetadata;
import kafka.javaapi.TopicMetadataRequest;
import kafka.javaapi.consumer.SimpleConsumer;
 
import java.util.*;
import java.util.Map.Entry;
 
public class KafkaOffsetTools {
public final static String KAFKA_TOPIC_NAME_ADAPTER = "sample";
public final static String KAFKA_TOPIC_NAME_EXCEPTION = "exception";
public final static String KAFKA_TOPIC_NAME_AUDIT = "audit";
private static final String rawTopicTotal = "rawTopicTotalRecordCounter";
private static final String avroTopicTotal = "avroTopicTotalRecordCounter";
private static final String exceptionTopicTotal = "exceptionTopicTotalRecordCounter";
 
public KafkaOffsetTools() {
}
 
public static long getLastOffset(SimpleConsumer consumer, String topic,
int partition, long whichTime, String clientName) {
TopicAndPartition topicAndPartition = new TopicAndPartition(topic,
partition);
Map, PartitionOffsetRequestInfo> requestInfo = new HashMap, PartitionOffsetRequestInfo>();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(
whichTime, 1));
kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(
requestInfo, kafka.api.OffsetRequest.CurrentVersion(),
clientName);
OffsetResponse response = consumer.getOffsetsBefore(request);
 
if (response.hasError()) {
System.err.println("Error fetching data Offset Data the Broker. Reason: " + response.errorCode(topic, partition));
return 0;
}
long[] offsets = response.offsets(topic, partition);
return offsets[0];
}
 
private TreeMap, PartitionMetadata> findLeader(List a_seedBrokers, String a_topic) {
TreeMap, PartitionMetadata> map = new TreeMap, PartitionMetadata>();
loop:
for (String seed : a_seedBrokers) {
SimpleConsumer consumer = null;
try {
String[] hostAndPort;
hostAndPort = seed.split(":");
consumer = new SimpleConsumer(hostAndPort[0], Integer.valueOf(hostAndPort[1]), 100000, 64 * 1024,
"leaderLookup" + new Date().getTime());
List topics = Collections.singletonList(a_topic);
TopicMetadataRequest req = new TopicMetadataRequest(topics);
kafka.javaapi.TopicMetadataResponse resp = consumer.send(req);
 
List metaData = resp.topicsMetadata();
for (TopicMetadata item : metaData) {
for (PartitionMetadata part : item.partitionsMetadata()) {
map.put(part.partitionId(), part);
}
}
} catch (Exception e) {
System.out.println("Error communicating with Broker [" + seed
+ "] to find Leader for [" + a_topic + ", ] Reason: " + e);
} finally {
if (consumer != null)
consumer.close();
}
}
return map;
}
 
public static void main(String[] args) {
String kafkaBrokerList = System.getenv("metadata.broker.list");
if(kafkaBrokerList == null || kafkaBrokerList.length() == 0){
System.err.println("No config kafka metadata.broker.list,it is null .");
//for test
kafkaBrokerList = "localhost:9092,localhost:9093";
System.err.println("Use this broker list for test,metadata.broker.list="+kafkaBrokerList);
}
//init topic,logSize = 0
Map,Integer> topics = new HashMap,Integer>();
topics.put(KAFKA_TOPIC_NAME_ADAPTER,0);
topics.put(KAFKA_TOPIC_NAME_EXCEPTION,0);
topics.put(KAFKA_TOPIC_NAME_AUDIT,0);
//init kafka broker list
String[] kafkaHosts;
kafkaHosts = kafkaBrokerList.split(",");
if (kafkaHosts == null || kafkaHosts.length == 0) {
System.err.println("No config kafka metadata.broker.list,it is null .");
System.exit(1);
}
List seeds = new ArrayList();
for (int i = 0; i < kafkaHosts.length; i++) {
seeds.add(kafkaHosts[i]);
}
 
KafkaOffsetTools kot = new KafkaOffsetTools();
 
for(String topicName : topics.keySet()){
TreeMap, PartitionMetadata> metadatas = kot.findLeader(seeds, topicName);
int logSize = 0;
for (Entry, PartitionMetadata> entry : metadatas.entrySet()) {
int partition = entry.getKey();
String leadBroker = entry.getValue().leader().host();
String clientName = "Client_" + topicName + "_" + partition;
SimpleConsumer consumer = new SimpleConsumer(leadBroker, entry.getValue().leader().port(), 100000,
64 * 1024, clientName);
long readOffset = getLastOffset(consumer, topicName, partition,
kafka.api.OffsetRequest.LatestTime(), clientName);
logSize += readOffset;
if (consumer != null) consumer.close();
}
topics.put(topicName,logSize);
}
System.out.println(topics.toString());
System.out.println(rawTopicTotal+"="+topics.get(KAFKA_TOPIC_NAME_ADAPTER)+" "+System.currentTimeMillis());
System.out.println(avroTopicTotal+"="+topics.get(KAFKA_TOPIC_NAME_AUDIT)+" "+System.currentTimeMillis());
System.out.println(exceptionTopicTotal+"="+topics.get(KAFKA_TOPIC_NAME_EXCEPTION)+" "+System.currentTimeMillis());
}
}

以上这篇kafka监控获取指定topic的消息总量示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现dnspod自动更新dns解析的方法
Feb 14 Python
Python中不同进制的语法及转换方法分析
Jul 27 Python
python字典DICT类型合并详解
Aug 17 Python
git进行版本控制心得详谈
Dec 10 Python
pandas把dataframe转成Series,改变列中值的类型方法
Apr 10 Python
Python paramiko模块的使用示例
Apr 11 Python
PYTHON发送邮件YAGMAIL的简单实现解析
Oct 28 Python
如何用OpenCV -python3实现视频物体追踪
Dec 04 Python
Win系统PyQt5安装和使用教程
Dec 25 Python
详解基于Jupyter notebooks采用sklearn库实现多元回归方程编程
Mar 25 Python
Python按照list dict key进行排序过程解析
Apr 04 Python
Django怎么在admin后台注册数据库表
Nov 14 Python
kafka-python 获取topic lag值方式
Dec 23 #Python
python3连接kafka模块pykafka生产者简单封装代码
Dec 23 #Python
python pyenv多版本管理工具的使用
Dec 23 #Python
Python测试Kafka集群(pykafka)实例
Dec 23 #Python
Python with语句和过程抽取思想
Dec 23 #Python
python每5分钟从kafka中提取数据的例子
Dec 23 #Python
Python彻底删除文件夹及其子文件方式
Dec 23 #Python
You might like
9个实用的PHP代码片段分享
2015/01/22 PHP
php数组键名技巧小结
2015/02/17 PHP
php5对象复制、clone、浅复制与深复制实例详解
2019/08/14 PHP
javascript检查日期格式的函数[比较全]
2008/10/17 Javascript
ExtJS GridPanel 根据条件改变字体颜色
2010/03/08 Javascript
javascript中String类的subString()方法和slice()方法
2011/05/24 Javascript
在JavaScript应用中使用RequireJS来实现延迟加载
2015/07/01 Javascript
比较常见的javascript中定义函数的区别
2015/11/09 Javascript
javascript实现2016新年版日历
2016/01/25 Javascript
Js+Ajax,Get和Post在使用上的区别小结
2016/06/08 Javascript
Bootstrap Table使用心得总结
2016/11/29 Javascript
Bootstrap基本插件学习笔记之折叠(22)
2016/12/08 Javascript
JS中append字符串包含onclick无效传递参数失败的解决方案
2016/12/26 Javascript
简单实现jQuery多选框功能
2017/01/09 Javascript
用director.js实现前端路由使用实例
2017/01/27 Javascript
用node-webkit把web应用打包成桌面应用(windows环境)
2018/02/01 Javascript
Vue中mintui的field实现blur和focus事件的方法
2018/08/25 Javascript
vue+web端仿微信网页版聊天室功能
2019/04/30 Javascript
简单了解JavaScript sort方法
2019/11/25 Javascript
Python中文件操作简明介绍
2015/04/13 Python
使用SAE部署Python运行环境的教程
2015/05/05 Python
Python ValueError: invalid literal for int() with base 10 实用解决方法
2015/06/21 Python
python3 实现的人人影视网站自动签到
2016/06/19 Python
Python之pandas读写文件乱码的解决方法
2018/04/20 Python
python得到电脑的开机时间方法
2018/10/15 Python
Django框架模型简单介绍与使用分析
2019/07/18 Python
解决Python对齐文本字符串问题
2019/08/28 Python
python matplotlib画盒图、子图解决坐标轴标签重叠的问题
2020/01/19 Python
美国经典刺绣和字母儿童服装特卖:Smocked Auctions
2018/07/16 全球购物
美国孕妇装购物网站:Motherhood Maternity
2019/09/22 全球购物
区域销售经理职责
2013/12/22 职场文书
爱情保证书
2015/01/17 职场文书
2016三八妇女节校园广播稿
2015/12/17 职场文书
用Python实现屏幕截图详解
2022/01/22 Python
动态规划之使用备忘录来改进Javascript函数
2022/04/07 Javascript
Vscode中SSH插件如何远程连接Linux
2022/05/02 Servers