解决KafkaConsumer多线程接入不安全问题(spark streaming 消费kafka)

使用场景:

设置并行度参数spark.streaming.concurrentJobs >1 时候,使用spark streaming消费kafka

异常信息:

There may be two or more tasks in one executor will use the same kafka consumer at the same time, then it will throw an exception: "KafkaConsumer is not safe for multi-threaded access"

JIRA-SPARK中已经提出的问题

https://issues.apache.org/jira/browse/SPARK-22606?jql=text ~ "spark.streaming.concurrentJobs"

解决办法:

第一种方案

PR地址:https://github.com/apache/spark/pull/19819

spark streaming消费kafka时候,默认开启了对kafkaconsumer进行缓存,通过存放到HashMap中实现,因此就需要有相应的key,才能找到具体到kafkaconsumer。

//原生的代码中是没有threadId变量的,通过加入线程id ,使得不同的线程不能同时使用同一个kafkaconsumer
 private case class CacheKey(groupId: String, topic: String, partition: Int, threadId: Long)
 
 private var cache: ju.LinkedHashMap[CacheKey, CachedKafkaConsumer[_, _]] = null
  
 CachedKafkaConsumer.get[K, V](groupId, part.topic, part.partition, threadId, kafkaParams)

这个办法其实就是为缓存在map中的CachedKafkaConsumer对应的key增加了一个参数是线程id,使得不让多个线程使用同一个consumer,但是这种情况每一个task都需要去创建一个consumer,是消耗资源的。
PR中这样一句评论:
It will create a new consumer for each thread. This could be quite resource consuming when several topics shared with thread pools.

第二种方案

对spark-streaming-kafka中的CacheKafkaConsumer进行了重构,首先介绍几个类


                
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值