Spark中广播变量和累加器

广播变量理解图:

广播变量使用:

val conf = new SparkConf()

conf.setMaster("local").setAppName("brocast")

val sc = new SparkContext(conf)

val list = List("hello xasxt")

val broadCast = sc.broadcast(list)

val lineRDD = sc.textFile("./words.txt")

lineRDD.filter { x => broadCast.value.contains(x) }.foreach { println}

sc.stop()

 注意事项

问: 能不能将一个RDD使用广播变量广播出去?

答:不能,因为RDD是不存储数据的。可以将RDD的结果广播出去。

广播变量只能在Driver端定义,不能在Executor端定义。

在Driver端可以修改广播变量的值,在Executor端无法修改广播变量的值。

累加器理解图:

累加器的使用:

val conf = new SparkConf()

conf.setMaster("local").setAppName("accumulator")

val sc = new SparkContext(conf)

val accumulator = sc.accumulator(0)

sc.textFile("./words.txt").foreach { x =>{accumulator.add(1)}}

println(accumulator.value)

sc.stop()

注意事项:

累加器在Driver端定义赋初始值,累加器只能在Driver端读取,在Excutor端更新。

原文地址:https://www.cnblogs.com/yehuili/p/10466377.html