无论是在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的更多相关文章

  1. 获取kafka最新offset-java

    之前笔者曾经写过通过scala的方式获取kafka最新的offset 但是大多数的情况我们需要使用java的方式进行获取最新offset scala的方式可以参考: http://www.cnblog ...

  2. Spark-Streaming获取kafka数据的两种方式:Receiver与Direct的方式

    简单理解为:Receiver方式是通过zookeeper来连接kafka队列,Direct方式是直接连接到kafka的节点上获取数据 Receiver 使用Kafka的高层次Consumer API来 ...

  3. 工具篇-Spark-Streaming获取kafka数据的两种方式(转载)

    转载自:https://blog.csdn.net/weixin_41615494/article/details/7952173 一.基于Receiver的方式 原理 Receiver从Kafka中 ...

  4. SparkStreaming获取kafka数据的两种方式:Receiver与Direct

    简介: Spark-Streaming获取kafka数据的两种方式-Receiver与Direct的方式,可以简单理解成: Receiver方式是通过zookeeper来连接kafka队列, Dire ...

  5. spark-streaming获取kafka数据的两种方式

    简单理解为:Receiver方式是通过zookeeper来连接kafka队列,Direct方式是直接连接到kafka的节点上获取数据 一.Receiver方式: 使用kafka的高层次Consumer ...

  6. 获取Kafka每个分区最新Offset的几种方法

    目录 脚本方法 Java 程序 参考资料 脚本方法 ./bin/kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhos ...

  7. 关于怎么获取kafka指定位置offset消息(转)

    1.在kafka中如果不设置消费的信息的话,一个消息只能被一个group.id消费一次,而新加如的group.id则会被“消费管理”记录,并指定从当前记录的消息位置开始向后消费.如果有段时间消费者关闭 ...

  8. 如何获取流式应用程序中checkpoint的最新offset

    对于流式应用程序,保证应用7*24小时的稳定运行,是非常必要的.因此对于计算引擎,要求必须能够适应与应用程序逻辑本身无关的问题(比如driver应用失败重启.网络问题.服务器问题.JVM崩溃等),具有 ...

  9. Scala创建SparkStreaming获取Kafka数据代码过程

    正文 首先打开spark官网,找一个自己用版本我选的是1.6.3的,然后进入SparkStreaming   ,通过搜索这个位置找到Kafka, 点击过去会找到一段Scala的代码 import or ...

随机推荐

  1. react在视频中截图,保存为base64位

    wq:之前看了网上很多教程,有点模糊,但是最后还是搞了出来 1  不要将视频放到canvas上面!  之前一直将video重新画到canvas上面,然后再次将第一个canvas放到第二个canvas上 ...

  2. 泛型(二)封装工具类CommonUtils-把一个Map转换成指定类型的javabean对象

    1.commons-beanutils的使用 commons-beanutils-1.9.3.jar 依赖 commons-logging-1.2.jar 代码1: String className ...

  3. [ZOJ3649]Social Net 题解

    前言 这道题目珂以说是很毒瘤了. 题解 首先克鲁斯卡尔求最大生成树,输出边权和. 倍增维护四个值:   链上最大值/最小值   链向上/向下最大差值 当然祖先是肯定要维护的. 然后把一条链经LCA分成 ...

  4. No 'Configuration' method was found in class 'WebApp.Startup

    The following errors occurred while attempting to load the app.- No 'Configuration' method was found ...

  5. 快速沃尔变换 FWT

    P4717 [模板]快速沃尔什变换 #include<bits/stdc++.h> using namespace std; #define int long long #define s ...

  6. Bug管理工具MantisBT-2.18.0安装教程

    Bug管理工具MantisBT安装教程 MantisBT官网下载地址:https://sourceforge.net/projects/mantisbt/# 写于:2018.12.1 如上传博客资料图 ...

  7. k8s中pod内dns无法解析的问题

    用k8s创建了pod,然后进入pod后,发现在pod中无法解析www.baidu.com,也就是出现了无法解析外面的域名的问题.经过高人指点,做个小总结.操作如下. 一,将CoreDNS 的Confi ...

  8. 启动Maven项目时报错Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean (default-clean) on project **-web: Failed to clean project: Failed to delete E:\**\target\tomcat\logs\access_lo

    这类错误 出现这种错误,通常是由于您已启动了另一个tomcat 进程或者运行的javaw.exe进程,导致报错. 解决方法: 1. 鼠标点击 X 进行关闭运行失败的 Console页,(如果运行多次, ...

  9. phpstudy composer 安装

    今天突然发现phpstudy 可以安装 composer 一打开php中openssl拓展 坑一  我的phpstudy 是2018最新版本,但是你下载laravel什么之类库会报错,是由于compo ...

  10. Sqlserver 创建账号

    下面是通过脚本创建账号,创建一个appuser 的账号,密码:123456,可操作的DB:TEST 赋予权限,增删改查,操作视图,存储过程.当然当前的账号要有足够的权限. create login a ...