获取kafka最新offset-scala
无论是在spark streaming消费kafka,或是监控kafka的数据时,我们经常会需要知道offset最新情况
kafka数据的topic基于分区,并且通过每个partition的主分区可以获取offset的最新情况
GetOffsetShellWrap
//这是对kafka自带工具包的扩展object GetOffsetShellWrap {
//在主函数添加一个参数map
def main(args: Array[String],map: ArrayBuffer[String]): Unit = { //对参数的解析
val parser = new OptionParser
val brokerListOpt = parser.accepts("broker-list", "REQUIRED: The list of hostname and port of the server to connect to.")
.withRequiredArg
.describedAs("hostname:port,...,hostname:port")
.ofType(classOf[String])
val topicOpt = parser.accepts("topic", "REQUIRED: The topic to get offset from.")
.withRequiredArg
.describedAs("topic")
.ofType(classOf[String])
val partitionOpt = parser.accepts("partitions", "comma separated list of partition ids. If not specified, it will find offsets for all partitions")
.withRequiredArg
.describedAs("partition ids")
.ofType(classOf[String])
.defaultsTo("")
val timeOpt = parser.accepts("time", "timestamp of the offsets before that")
.withRequiredArg
.describedAs("timestamp/-1(latest)/-2(earliest)")
.ofType(classOf[java.lang.Long])
val nOffsetsOpt = parser.accepts("offsets", "number of offsets returned")
.withRequiredArg
.describedAs("count")
.ofType(classOf[java.lang.Integer])
.defaultsTo(1)
val maxWaitMsOpt = parser.accepts("max-wait-ms", "The max amount of time each fetch request waits.")
.withRequiredArg
.describedAs("ms")
.ofType(classOf[java.lang.Integer])
.defaultsTo(1000)
if(args.length == 0)
CommandLineUtils.printUsageAndDie(parser, "An interactive shell for getting consumer offsets.")
val options = parser.parse(args : _*)
CommandLineUtils.checkRequiredArgs(parser, options, brokerListOpt, topicOpt, timeOpt)
//获取参数的值
val clientId = "GetOffsetShell"
val brokerList = options.valueOf(brokerListOpt)
ToolsUtils.validatePortOrDie(parser, brokerList)
val metadataTargetBrokers = ClientUtils.parseBrokerList(brokerList)
val topic = options.valueOf(topicOpt)
var partitionList = options.valueOf(partitionOpt)
var time = options.valueOf(timeOpt).longValue
val nOffsets = options.valueOf(nOffsetsOpt).intValue
val maxWaitMs = options.valueOf(maxWaitMsOpt).intValue()
val topicsMetadata = ClientUtils.fetchTopicMetadata(Set(topic), metadataTargetBrokers, clientId, maxWaitMs).topicsMetadata
if(topicsMetadata.size != 1 || !topicsMetadata(0).topic.equals(topic)) {
System.err.println(("Error: no valid topic metadata for topic: %s, " + " probably the topic does not exist, run ").format(topic) +
"kafka-list-topic.sh to verify")
System.exit(1)
}
val partitions =
if(partitionList == "") {
topicsMetadata.head.partitionsMetadata.map(_.partitionId)
} else {
partitionList.split(",").map(_.toInt).toSeq
} //遍历每个主分区
partitions.foreach { partitionId =>
val partitionMetadataOpt = topicsMetadata.head.partitionsMetadata.find(_.partitionId == partitionId)
partitionMetadataOpt match {
case Some(metadata) =>
metadata.leader match {
case Some(leader) =>
val consumer = new SimpleConsumer(leader.host, leader.port, 10000, 100000, clientId)
val topicAndPartition = TopicAndPartition(topic, partitionId)
val request = OffsetRequest(Map(topicAndPartition -> PartitionOffsetRequestInfo(time, nOffsets)))
val offsets = consumer.getOffsetsBefore(request).partitionErrorAndOffsets(topicAndPartition).offsets
//把获取到的offset进行存储
map += "%s:%d:%s".format(topic, partitionId, offsets.mkString(","))
case None => System.err.println("Error: partition %d does not have a leader. Skip getting offsets".format(partitionId))
}
case None => System.err.println("Error: partition %d does not exist".format(partitionId))
}
}
}
}
GetOffsetShellWrapScalaTest
object GetOffsetShellWrapScalaTest {
def main(args: Array[String]) {
var arr = ArrayBuffer[String]();
arr+="--broker-list=hadoop-01:9092"
arr+="-topic=2017-11-6-test"
arr+="--time=-1"
val resule = getOffset(arr.toArray)
for(i<-resule){
println("我自己获取到的偏移量=> "+i)
}
}
def getOffset(args: Array[String]) : Array[String]={
val map = new ArrayBuffer[String]()
GetOffsetShellWrap.main(args.toArray,map)
map.toArray
}
}
结果输出:
2017-11-6-test:2:16099 2017-11-6-test:1:15930 2017-11-6-test:0:16096

获取kafka最新offset-scala的更多相关文章
- 获取kafka最新offset-java
之前笔者曾经写过通过scala的方式获取kafka最新的offset 但是大多数的情况我们需要使用java的方式进行获取最新offset scala的方式可以参考: http://www.cnblog ...
- Spark-Streaming获取kafka数据的两种方式:Receiver与Direct的方式
简单理解为:Receiver方式是通过zookeeper来连接kafka队列,Direct方式是直接连接到kafka的节点上获取数据 Receiver 使用Kafka的高层次Consumer API来 ...
- 工具篇-Spark-Streaming获取kafka数据的两种方式(转载)
转载自:https://blog.csdn.net/weixin_41615494/article/details/7952173 一.基于Receiver的方式 原理 Receiver从Kafka中 ...
- SparkStreaming获取kafka数据的两种方式:Receiver与Direct
简介: Spark-Streaming获取kafka数据的两种方式-Receiver与Direct的方式,可以简单理解成: Receiver方式是通过zookeeper来连接kafka队列, Dire ...
- spark-streaming获取kafka数据的两种方式
简单理解为:Receiver方式是通过zookeeper来连接kafka队列,Direct方式是直接连接到kafka的节点上获取数据 一.Receiver方式: 使用kafka的高层次Consumer ...
- 获取Kafka每个分区最新Offset的几种方法
目录 脚本方法 Java 程序 参考资料 脚本方法 ./bin/kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhos ...
- 关于怎么获取kafka指定位置offset消息(转)
1.在kafka中如果不设置消费的信息的话,一个消息只能被一个group.id消费一次,而新加如的group.id则会被“消费管理”记录,并指定从当前记录的消息位置开始向后消费.如果有段时间消费者关闭 ...
- 如何获取流式应用程序中checkpoint的最新offset
对于流式应用程序,保证应用7*24小时的稳定运行,是非常必要的.因此对于计算引擎,要求必须能够适应与应用程序逻辑本身无关的问题(比如driver应用失败重启.网络问题.服务器问题.JVM崩溃等),具有 ...
- Scala创建SparkStreaming获取Kafka数据代码过程
正文 首先打开spark官网,找一个自己用版本我选的是1.6.3的,然后进入SparkStreaming ,通过搜索这个位置找到Kafka, 点击过去会找到一段Scala的代码 import or ...
随机推荐
- ESP8266内置的定时器库--Ticker库
Ticker的功能非常简单,就是规定时间后调用函数 总体上,根据功能可以把方法分为两大类: 定时器管理方法: 定时器启用方法: detach() 停止定时器 active() 定时器是否 ...
- The Preliminary Contest for ICPC Asia Shanghai 2019 D. Counting Sequences I
题目:https://nanti.jisuanke.com/t/41412思路:dfs 先取ai>2 2^12>3000 因此至多取11个 其余用1补 ...
- maven 三个仓库表
https://search.maven.org ,http://www.mvnrepository.com/ http://maven.apache.org
- js中[]、{}、()区别
一.{ } 大括号,表示定义一个对象,大部分情况下要有成对的属性和值,或是函数体 {}表示对象.[]表示对象的属性.方法,()如果用在方法名后面,代表调用 如:var LangShen = {&quo ...
- Linux 环境下 gzip 的加解密命令
1.加密 [root@127-0-0-1 nginx]# gzip -v access.log-20190328 access.log-20190328: 95.8% -- replaced with ...
- 设置获取data-*属性值
html代码如下: <div id="getId" data-id="122" data-vice-id="11">获取id&l ...
- 【转载】自动化运维系列之Cobbler给Openstack节点安装操作系统
preface 我们在一篇博文知道了如何搭建Cobbler,那么下面就通过Cobbler来安抓Openstack所有节点吧. 服务器配置信息如下: 主机名 IP 角色 Cobbler.node.com ...
- ArrayList,Vector ,LinkedList的存储性能和特性
ArrayList,Vector,LinkedList : 两者都采用数组元素方式存储数据,此数组元素数大于实际存储的数据(以便于增加和插入元素),允许直接按照序号索引元素,但是插入元素涉及数组元素移 ...
- python3.x使用cxfreeze将.p打包成.exe
之前写了一个使用ffplay批量查看格式为h264的图片,每次抽帧后都要打开pycharm编译器来运行程序,然后才能正常查看图片,或者在其他没有安装python环境的电脑中运行,很不方便.为此,在网上 ...
- WebClient上传下载文件,小白篇
WebClient的上传文件一直报错,各种百度各种稀奇古怪的东西,终于百度到一篇小白学习篇 转自: https://www.cnblogs.com/cncc/p/5722231.html 使用C#We ...