转载自:http://blog.csdn.net/xueba207/article/details/51135423

问题描述

笔者使用spark streaming读取Kakfa中的数据,做进一步处理,用到了KafkaUtil的createDirectStream()方法;该方法不会自动保存topic partition的offset到zk,需要在代码中编写提交逻辑,此处介绍了保存offset的方法。 
当删除已经使用过的kafka topic,然后新建同名topic,使用该方式时出现了"numRecords
must not be negative"
异常 
详细信息如下图: 

是不合法的参数异常,RDD的记录数目必须不能是负数。 
下文详细分析该问题的出现的场景,以及解决方法。

异常分析

numRecords确定

首先,定位出异常出现的问题,和大致原因。异常中打印出了出现的位置 org.apache.spark.streaming.scheduler.StreamInputInfo.InputInfoTracker的第38行,此处代码:

代码38行,判断了numRecords是否大于等于0,当不满足条件时抛出异常,可判断此时numRecords<0。 
numRecords的解释: 
numRecords: the number of records in a batch 
应该是当前rdd中records 数目计算出了问题。 
numRecords 构造StreamInputInfo时的参数,结合异常中的信息,找到了DirectKafkaInputDStream中的构造InputInfo的位置: 

可知 numRecords是rdd.count()的值。

rdd.count的计算

根据以上分析可知rdd.count()值为负值,因此需要分析rdd的是如何生成的。 
同样在DirectKafkaInputDStream中找到rdd的生成代码:

从此处一路跟踪代码,可在KafkaRDD.scala中找到rdd.count的赋值逻辑:

offsetRanges的计算逻辑

offsetRanges的定义

offsetRanges: offset ranges that define the Kafka data
belonging to this RDD

在KafkaRDDPartition 40行找到kafka partition offsetRange的计算逻辑:

def count(): Long = untilOffset - fromOffset 
fromOffset: per-topic/partition Kafka offset defining
the (inclusive) starting point of the batch
 
untilOffset: per-topic/partition Kafka offset defining
the (inclusive) ending point of the batch

fromOffset来自zk中保存; 
untilOffset通过DirectKafkaInputDStream第145行:

val untilOffsets = clamp(latestLeaderOffsets(maxRetries))

计算得到,计算过程得到最新的offset,然后使用spark.streaming.kafka.maxRatePerPartition做clamp,得到允许的最大untilOffsets,##而此时新建的topic,如果topic中没有数据,untilOffsets应该为0##

原因总结

当删除一个topic时,zk中的offset信息并没有被清除,因此KafkaDirectStreaming再次启动时仍会得到旧的topic offset为old_offset,作为fromOffset。 
当新建了topic后,使用untiloffset计算逻辑,得到untilOffset为0(如果topic已有数据则>0); 
再次被启动的KafkaDirectStreaming Job通过异常的计算逻辑得到的rdd numRecords值为可计算为: 
numRecords = untilOffset - fromOffset(old_offset) 
当untilOffset < old_offset时,此异常会出现,对于新建的topic这种情况的可能性很大

解决方法

思路

根据以上分析,可在确定KafkaDirectStreaming 的fromOffsets时判断fromOffset与untiloffset的大小关系,当untilOffset < fromOffset时,矫正fromOffset为offset初始值0。

流程

  • 从zk获取topic/partition 的fromOffset(获取方法链接
  • 利用SimpleConsumer获取每个partiton的lastOffset(untilOffset )
  • 判断每个partition lastOffset与fromOffset的关系
  • 当lastOffset < fromOffset时,将fromOffset赋值为0 
    通过以上步骤完成fromOffset的值矫正。

核心代码

获取kafka topic partition lastoffset代码:


  1. package org.frey.example.utils.kafka;
  2. import com.google.common.collect.Lists;
  3. import com.google.common.collect.Maps;
  4. import kafka.api.PartitionOffsetRequestInfo;
  5. import kafka.cluster.Broker;
  6. import kafka.common.TopicAndPartition;
  7. import kafka.javaapi.*;
  8. import kafka.javaapi.consumer.SimpleConsumer;
  9. import java.util.Date;
  10. import java.util.HashMap;
  11. import java.util.List;
  12. import java.util.Map;
  13. /**
  14. * KafkaOffsetTool
  15. *
  16. * @author v1-daddy
  17. * @date 2016/4/11
  18. */
  19. public class KafkaOffsetTool {
  20. private static KafkaOffsetTool instance;
  21. final int TIMEOUT = 100000;
  22. final int BUFFERSIZE = 64 * 1024;
  23. private KafkaOffsetTool() {
  24. }
  25. public static synchronized KafkaOffsetTool getInstance() {
  26. if (instance == null) {
  27. instance = new KafkaOffsetTool();
  28. }
  29. return instance;
  30. }
  31. public Map<TopicAndPartition, Long> getLastOffset(String brokerList, List<String> topics,
  32. String groupId) {
  33. Map<TopicAndPartition, Long> topicAndPartitionLongMap = Maps.newHashMap();
  34. Map<TopicAndPartition, Broker> topicAndPartitionBrokerMap =
  35. KafkaOffsetTool.getInstance().findLeader(brokerList, topics);
  36. for (Map.Entry<TopicAndPartition, Broker> topicAndPartitionBrokerEntry : topicAndPartitionBrokerMap
  37. .entrySet()) {
  38. // get leader broker
  39. Broker leaderBroker = topicAndPartitionBrokerEntry.getValue();
  40. SimpleConsumer simpleConsumer = new SimpleConsumer(leaderBroker.host(), leaderBroker.port(),
  41. TIMEOUT, BUFFERSIZE, groupId);
  42. long readOffset = getTopicAndPartitionLastOffset(simpleConsumer,
  43. topicAndPartitionBrokerEntry.getKey(), groupId);
  44. topicAndPartitionLongMap.put(topicAndPartitionBrokerEntry.getKey(), readOffset);
  45. }
  46. return topicAndPartitionLongMap;
  47. }
  48. /**
  49. * 得到所有的 TopicAndPartition
  50. *
  51. * @param brokerList
  52. * @param topics
  53. * @return topicAndPartitions
  54. */
  55. private Map<TopicAndPartition, Broker> findLeader(String brokerList, List<String> topics) {
  56. // get broker's url array
  57. String[] brokerUrlArray = getBorkerUrlFromBrokerList(brokerList);
  58. // get broker's port map
  59. Map<String, Integer> brokerPortMap = getPortFromBrokerList(brokerList);
  60. // create array list of TopicAndPartition
  61. Map<TopicAndPartition, Broker> topicAndPartitionBrokerMap = Maps.newHashMap();
  62. for (String broker : brokerUrlArray) {
  63. SimpleConsumer consumer = null;
  64. try {
  65. // new instance of simple Consumer
  66. consumer = new SimpleConsumer(broker, brokerPortMap.get(broker), TIMEOUT, BUFFERSIZE,
  67. "leaderLookup" + new Date().getTime());
  68. TopicMetadataRequest req = new TopicMetadataRequest(topics);
  69. TopicMetadataResponse resp = consumer.send(req);
  70. List<TopicMetadata> metaData = resp.topicsMetadata();
  71. for (TopicMetadata item : metaData) {
  72. for (PartitionMetadata part : item.partitionsMetadata()) {
  73. TopicAndPartition topicAndPartition =
  74. new TopicAndPartition(item.topic(), part.partitionId());
  75. topicAndPartitionBrokerMap.put(topicAndPartition, part.leader());
  76. }
  77. }
  78. } catch (Exception e) {
  79. e.printStackTrace();
  80. } finally {
  81. if (consumer != null)
  82. consumer.close();
  83. }
  84. }
  85. return topicAndPartitionBrokerMap;
  86. }
  87. /**
  88. * get last offset
  89. * @param consumer
  90. * @param topicAndPartition
  91. * @param clientName
  92. * @return
  93. */
  94. private long getTopicAndPartitionLastOffset(SimpleConsumer consumer,
  95. TopicAndPartition topicAndPartition, String clientName) {
  96. Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo =
  97. new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
  98. requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(
  99. kafka.api.OffsetRequest.LatestTime(), 1));
  100. OffsetRequest request = new OffsetRequest(
  101. requestInfo, kafka.api.OffsetRequest.CurrentVersion(),
  102. clientName);
  103. OffsetResponse response = consumer.getOffsetsBefore(request);
  104. if (response.hasError()) {
  105. System.out
  106. .println("Error fetching data Offset Data the Broker. Reason: "
  107. + response.errorCode(topicAndPartition.topic(), topicAndPartition.partition()));
  108. return 0;
  109. }
  110. long[] offsets = response.offsets(topicAndPartition.topic(), topicAndPartition.partition());
  111. return offsets[0];
  112. }
  113. /**
  114. * 得到所有的broker url
  115. *
  116. * @param brokerlist
  117. * @return
  118. */
  119. private String[] getBorkerUrlFromBrokerList(String brokerlist) {
  120. String[] brokers = brokerlist.split(",");
  121. for (int i = 0; i < brokers.length; i++) {
  122. brokers[i] = brokers[i].split(":")[0];
  123. }
  124. return brokers;
  125. }
  126. /**
  127. * 得到broker url 与 其port 的映射关系
  128. *
  129. * @param brokerlist
  130. * @return
  131. */
  132. private Map<String, Integer> getPortFromBrokerList(String brokerlist) {
  133. Map<String, Integer> map = new HashMap<String, Integer>();
  134. String[] brokers = brokerlist.split(",");
  135. for (String item : brokers) {
  136. String[] itemArr = item.split(":");
  137. if (itemArr.length > 1) {
  138. map.put(itemArr[0], Integer.parseInt(itemArr[1]));
  139. }
  140. }
  141. return map;
  142. }
  143. public static void main(String[] args) {
  144. List<String> topics = Lists.newArrayList();
  145. topics.add("ys");
  146. topics.add("bugfix");
  147. Map<TopicAndPartition, Long> topicAndPartitionLongMap =
  148. KafkaOffsetTool.getInstance().getLastOffset("broker001:9092,broker002:9092", topics, "my.group.id");
  149. for (Map.Entry<TopicAndPartition, Long> entry : topicAndPartitionLongMap.entrySet()) {
  150. System.out.println(entry.getKey().topic() + "-"+ entry.getKey().partition() + ":" + entry.getValue());
  151. }
  152. }
  153. }

矫正offset核心代码:


  1. /** 以下 矫正 offset */
  2. // 得到Topic/partition 的lastOffsets
  3. Map<TopicAndPartition, Long> topicAndPartitionLongMap =
  4. KafkaOffsetTool.getInstance().getLastOffset(kafkaParams.get("metadata.broker.list"),
  5. topicList, "my.group.id");
  6. // 遍历每个Topic.partition
  7. for (Map.Entry<TopicAndPartition, Long> topicAndPartitionLongEntry : fromOffsets.entrySet()) {
  8. // fromOffset > lastOffset时
  9. if (topicAndPartitionLongEntry.getValue() >
  10. topicAndPartitionLongMap.get(topicAndPartitionLongEntry.getKey())) {
  11. //矫正fromoffset为offset初始值0
  12. topicAndPartitionLongEntry.setValue(0L);
  13. }
  14. }
  15. /** 以上 矫正 offset */​

Spark Streaming 'numRecords must not be negative'问题解决的更多相关文章

  1. Spark Streaming Backpressure分析

    1.为什么引入Backpressure 默认情况下,Spark Streaming通过Receiver以生产者生产数据的速率接收数据,计算过程中会出现batch processing time > ...

  2. spark streaming之三 rdd,job的动态生成以及动态调度

    前面一篇讲到了,DAG静态模板的生成.那么spark streaming会在每一个batch时间一到,就会根据DAG所形成的逻辑以及物理依赖链(dependencies)动态生成RDD以及由这些RDD ...

  3. Spark Streaming性能优化: 如何在生产环境下应对流数据峰值巨变

    1.为什么引入Backpressure 默认情况下,Spark Streaming通过Receiver以生产者生产数据的速率接收数据,计算过程中会出现batch processing time > ...

  4. Spark Streaming性能优化系列-怎样获得和持续使用足够的集群计算资源?

    一:数据峰值的巨大影响 1. 数据确实不稳定,比如晚上的时候訪问流量特别大 2. 在处理的时候比如GC的时候耽误时间会产生delay延迟 二:Backpressure:数据的反压机制 基本思想:依据上 ...

  5. Spark Streaming应用启动过程分析

    本文为SparkStreaming源码剖析的第三篇,主要分析SparkStreaming启动过程. 在调用StreamingContext.start方法后,进入JobScheduler.start方 ...

  6. spark streaming限制吞吐

    使用spark.streaming.receiver.maxRate这个属性限制每秒的最大吞吐.官方文档如下: Maximum rate (number of records per second) ...

  7. Spark Streaming ReceiverTracker架构设计

    本节的主要内容: 一.ReceiverTracker的架构设计 二.消息循环系统 三.ReceiverTracker具体实现 Spark Streaming作为Spark Core基础 架构之上的一个 ...

  8. Spark Streaming 总结

    这篇文章记录我使用 Spark Streaming 进行 ETL 处理的总结,主要包含如何编程,以及遇到的问题. 环境 我在公司使用的环境如下: Spark: 2.2.0 Kakfa: 0.10.1 ...

  9. spark streaming 接收kafka消息之四 -- 运行在 worker 上的 receiver

    使用分布式receiver来获取数据使用 WAL 来实现 exactly-once 操作: conf.set("spark.streaming.receiver.writeAheadLog. ...

随机推荐

  1. [Jenkins] 配置任务中的坑s

    Jenkins 坑1:sh: adb: command not found 背景:在任务中使用了adb命令 adb 使用时要在服务器上配Android-home的环境变量的 配置完成之后发现在服务器上 ...

  2. redis特性,使用场景

    redis特性: 1.redis保存在内存中,读写速度快. 2.redis--持久化(断电数据不丢失:对数据的更新将异步保存到磁盘上). 3.redis数据结构丰富 4.redis功能丰富 5.简单( ...

  3. CCF关于NOIP复赛网络申诉问题的公告

    CCF NOI竞赛委员会将NOIP复赛网络申诉的有关情况公告如下.凡属于以下情况的申诉,均不予受理 1.非公示期限内提出的申诉,不予受理: 2.与个人名次.他人成绩和他人名次有关的申诉,不予受理: 3 ...

  4. Python之路-文件操作(py3)

    文件操作的基本步骤: 1.打开文件:f=open('filename'),with open('filename') as f 2.操作文件:增,删,改,查 3.关闭文件:f.close 打开文件 p ...

  5. springCloud配置本地配中心SpringCloudConfig

    多环境配置 在一般开发过程中如果调试都在本地进行,则可以设置一个多环境配置,在本地与线上配置间来回切换. springcloud默认会访问的配置文件名是application.properties, ...

  6. ionic1 添加百度地图插件 cordova-plugin-baidumaplocation

    cordova-plugin-baidumaplocation 这个插件返回的数据是 json 格式的  可以直接获取  android 和 ios 都可用 1.先去百度地图平台去创建应用  获取访问 ...

  7. jsoncpp

    1.y.z is built with C++11. 0.y.z can be used with older compilers 1.y.z 版本是基于C++11的:0.y.z 是基于老版本的,为了 ...

  8. My First Linux Module

    My First Linux Module Today, I successfully build my first linux hello module. First of all add a di ...

  9. idea取消参数名称(形参名)提示

    idea取消参数名称(形参名)提示 IDEA会自动显示形式参数的变量名称,这在一开始使用时感觉很方便,友好.有时候也会显得排版很乱,下面是取消自动显示形式参数名称的方式 取消前是这个样子. “File ...

  10. 解决Arcgis相同投影仍出现偏差的问题

    网上下载了一个土地利用分类的polygon矢量图---导入arcgis--投影不是我想要的.出现了一些偏差 立即转换投影----按照网上教程--先定义投影-再定义坐标系---结果很糟糕,inconsi ...