FlinkKafkaConsumer源码分析

参考:
https://www.jianshu.com/p/f6f135855e42
https://www.jianshu.com/p/40c592186502

FlinkKafkaConsumer<T> extends FlinkKafkaConsumerBase<T> 
1、initializeState  
   初始化unionOffsetStates 存放offset    数据结构为ListState<Tuple2<KafkaTopicPartition, Long>>   一个subtask可以消费多个partition,所以是list 
   判断是否restore 如果是,将 unionOffsetStates 赋值给内存 restoredState 数据结构为 TreeMap<KafkaTopicPartition, Long> 

2open 
   设置提交offset的模式    ON_CHECKPOINTS KAFKA_PERIODIC DISABLED
   创建和分区发现工具 createPartitionDiscoverer
   创建出一个KafkaConsumer this.partitionDiscoverer.open() -> initializeConnections -> this.kafkaConsumer = new KafkaConsumer<>(kafkaProperties);
   获取所有fixedTopics和匹配topicPattern的Topic包含的所有分区信息
        partitionDiscoverer.discoverPartitions() -> getAllPartitionsForTopics(isFixedTopics)  ->  List<PartitionInfo> kafkaPartitions = kafkaConsumer.partitionsFor(topic)
                                             		getAllTopics(正则匹配) -> kafkaConsumer.listTopics() -> isMatchingTopic(正则匹配) -> getAllPartitionsForTopics
   并通过分区分配器为当前subtask的kafkaconsumer分配kafka分区
        partitionDiscoverer.discoverPartitions() -> setAndCheckDiscoveredPartition -> KafkaTopicPartitionAssigner.assign(partition, numParallelSubtasks) == indexOfThisSubtask
   判断是否从快照恢复
       从快照恢复:通过分区分配器找到当前subtask的kafkaconsumer分配的kafka分区 放入 subscribedPartitionsToStartOffsets( Map<KafkaTopicPartition, Long>订阅的分区和起始offset信息)
	               如果修改了并行度或者kafka新增了分区会导致重分配  参考 
       不从快照恢复:StartupMode:GROUP_OFFSETS,EARLIEST,LATEST,TIMESTAMP,SPECIFIC_OFFSETS
	   
3、run
   创建一个 kafkaFetcher  createFetcher -> public KafkaFetcher
       创建 unassignedPartitionsQueue   super -> this.unassignedPartitionsQueue = new ClosableBlockingQueue<>();
			ClosableBlockingQueue<KafkaTopicPartitionState<T, KPH>> unassignedPartitionsQueue
			当初始化时会把需要消费的 TopicPartition 加入这个队列;如果启动了 TopicPartition 周期性自动发现,那么后续新发现 TopicPartition 也会加入这个队列
       创建 Handover  this.handover = new Handover()  可以理解为一个长度为一的阻塞队列,将 consumerThread 获取的消息或者抛出的异常,传递给 flink 执行的线程
	   创建kafkaconsumerThread  this.consumerThread = new KafkaConsumerThread
	        封装了 Kafka 消费的逻辑,另外依靠 unassignedPartitionsQueue,可以动态添加新的 TopicPartition。
            封装了 offset 提交的逻辑,如果提交策略是 OffsetCommitMode.ON_CHECKPOINTS,那么利用 CheckpointListener 的回调执行 offset 提交,
			其中线程间通信使用了 nextOffsetsToCommit 这个数据结构

   判断是否开启分区发现
       (1)、开启分区发现:启动定期分区发现任务和数据获取任务
	       runWithPartitionDiscovery -> createAndStartDiscoveryLoop{
		     // 发现新分区
		     discoveredPartitions = partitionDiscoverer.discoverPartitions();
			 如果发现新的分区,并且数据源running,则添加新分区
			 if(running && !discoveredPartitions.isEmpty()) {
				kafkaFetcher.addDiscoveredPartitions(discoveredPartitions);  
				   // 新发现 TopicPartition 也会加入ClosableBlockingQueue<KafkaTopicPartitionState<T, KPH>> unassignedPartitionsQueue 队列
				   -> unassignedPartitionsQueue.add(newPartitionState);
			 }
		   }
		   kafkaFetcher.runFetchLoop() 
		   
	       启动kafka消费线程,定期从kafkaConsumer拉取数据并转交给handover对象,handover 将 consumerThread 获取的消息或者抛出的异常,传递给 flink 执行的线程
		      consumerThread.start() -> KafkaConsumerThread.run  -> while(running) {
			      如果有offset需要提交就先提交offset
				  if(!commitInProgress) {
				     consumer.commitAsync
				  }
				  //-------分区发现原理----------------
					/**
					 * 为consumer指定新的分区
					 * 由于分区发现功能的存在,consumer需要添加新发现的分区,否则poll数据会报错
					 *   第一次进来 hasAssignedPartitions 为 false
					 *      newPartitions = unassignedPartitionsQueue.getBatchBlocking(); 	nonEmpty.await();
					 *      这是个阻塞方法,等待 主线程 获取分区信息 加入 unassignedPartitionsQueue
					 *        run -> runWithPartitionDiscovery -> createAndStartDiscoveryLoop
					 *          ->  partitionDiscoverer.discoverPartitions()
					 *          ->  kafkaFetcher.addDiscoveredPartitions(discoveredPartitions);
					 *            -> unassignedPartitionsQueue.add(newPartitionState){
					 *                elements.addLast(element);
					 *                nonEmpty.signalAll();  通知阻塞线程 getBatchBlocking 执行
					 *            }
					 *       unassignedPartitionsQueue.getBatchBlocking() 解除阻塞 返回 新增分区 newPartitions
					 *
					 *  reassignPartitions(newPartitions); 重分配消费分区 并将hasAssignedPartitions 置为 ture
					 *  后面来这里的时候都是走 这步 newPartitions = unassignedPartitionsQueue.pollBatch();
					 *  不阻塞,有新发现的分区就走重分区,没有就返回null
					 */
					try {
						if(hasAssignedPartitions) {
							newPartitions = unassignedPartitionsQueue.pollBatch();
						} else {
							newPartitions = unassignedPartitionsQueue.getBatchBlocking();
						}
						if(newPartitions != null) {
							// TODO 重点, kafka重分配消费分区
							reassignPartitions(newPartitions);
						}
					} catch(AbortedReassignmentException e) {
						continue;
					}				  
				  
				  //-----------------------------------
				  
				  // poll kafka数据
				  records = consumer.poll(pollTimeout)
				  // 将数据交给handover
				  handover.produce(records);
			  }
			  handover.pollNext()
			  partitionConsumerRecordsHandler -> emitRecordsWithTimestamps(发送给flink执行的线程)

	  (2)、未开启分区发现:直接拉取数据  kafkaFetcher.runFetchLoop();

4、snapshotState
   如果KafkaFetcher尚未初始化完毕。需要保存已订阅的topic连同他们的初始offset
   如果KafkaFetcher已初始化完毕,调用fetcher的snapshotCurrentState方法,获取当前offset 
   如果offsetCommitMode为ON_CHECKPOINTS类型,还需要将topic和offset写入到pendingOffsetsToCommit集合中,该集合用于checkpoint成功的时候向Kafka broker提交offset
   并放入 unionOffsetStates 状态中,从checkpoint恢复时使用
   重点看 fetcher.snapshotCurrentState(){ // AbstractFetcher
        HashMap<KafkaTopicPartition, Long> state = new HashMap<>(subscribedPartitionStates.size());
		for (KafkaTopicPartitionState<T, KPH> partition : subscribedPartitionStates) {
			state.put(partition.getKafkaTopicPartition(), partition.getOffset());
		}
   }
   pendingOffsetsToCommit.put(context.getCheckpointId(), currentOffsets);
   for(Map.Entry<KafkaTopicPartition, Long> kafkaTopicPartitionLongEntry : currentOffsets.entrySet()) {
	   unionOffsetStates.add(Tuple2.of(kafkaTopicPartitionLongEntry.getKey(), kafkaTopicPartitionLongEntry.getValue()));
   }
   再来看 subscribedPartitionStates 是怎样加入最新的offset的
   FlinkKafkaConsumerBase.run -> runFetchLoop{
      consumerThread.start();
      while(true){
	     final ConsumerRecords<byte[], byte[]> records = handover.pollNext();
		 for(KafkaTopicPartitionState<T, TopicPartition> partition : subscribedPartitionStates()) {
		 	List<ConsumerRecord<byte[], byte[]>> partitionRecords = records.records(partition.getKafkaPartitionHandle());
		 	// TODO ->
		 	partitionConsumerRecordsHandler(partitionRecords, partition);
		 }
	  }
   }
   // kafka数据一条一条发送出去的时候,更新最新的offset放入partitionState==subscribedPartitionStates
   partitionConsumerRecordsHandler -> emitRecordsWithTimestamps -> partitionState.setOffset(offset)

5、notifyCheckpointComplete
   从 pendingOffsetsToCommit 取出对应 checkpoint 的 offsets 提交
   kafkaconsumerThread 的while true循环里先通过nextOffsetsToCommit.getAndSet检查有无新的要commit消息,有的话就使用consumer.commitAsync 异步提交offset
    int posInMap = pendingOffsetsToCommit.indexOf(checkpointId)
	Map<KafkaTopicPartition, Long> offsets = (Map<KafkaTopicPartition, Long>) pendingOffsetsToCommit.remove(posInMap)
	fetcher.commitInternalOffsetsToKafka(offsets, offsetCommitCallback) -> doCommitInternalOffsetsToKafka
	   -> consumerThread.setOffsetsToCommit(offsetsToCommit, commitCallback);
	   /**
		 * 原子操作 乐观锁
		 * nextOffsetsToCommit.getAndSet(Tuple2.of(offsetsToCommit, commitCallback))
		 *   Tuple2.of(offsetsToCommit, commitCallback) 是 newValue
		 * 在这里设置 nextOffsetsToCommit 要提交的offset
		 *
		 * 下文的 consumerThread.run 里面
		 * final Tuple2<Map<TopicPartition, OffsetAndMetadata>, KafkaCommitCallback> commitOffsetsAndCallback
		 *        = nextOffsetsToCommit.getAndSet(null)
		 * 获取 设置的 要提交的offset 后通过
		 *    consumer.commitAsync(commitOffsetsAndCallback.f0, new CommitCallback(commitOffsetsAndCallback.f1));
		 * 异步提交offset
		 */
		if(nextOffsetsToCommit.getAndSet(Tuple2.of(offsetsToCommit, commitCallback)) != null) 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值