Broadcast Variable

Spark提供的Broadcast Variable,是只读的。并且在每个节点上只会有一份副本,而不会为每个task都拷贝一份副本。因此其最大作用,就是减少变量到各个节点的网络传输消耗,以及在各个节点上的内存消耗。此外,spark自己内部也使用了高效的广播算法来减少网络消耗。

可以通过调用SparkContext的broadcast()方法,来针对某个变量创建广播变量。然后在算子的函数内,使用到广播变量时,每个节点只会拷贝一份副本了。每个节点可以使用广播变量的value()方法获取值。记住,广播变量,是只读的。
val factor = 3
val factorBroadcast = sc.broadcast(factor)

val arr = Array(1, 2, 3, 4, 5)
val rdd = sc.parallelize(arr)
val multipleRdd = rdd.map(num => num * factorBroadcast.value())

multipleRdd.foreach(num => println(num))

Java版本案例

public class BroadcastVariable {

​public static void main(String[] args) {

​​SparkConf conf = new SparkConf().setAppName("BroadcastVariable")​​​​.setMaster("local");

JavaSparkContext sc = new JavaSparkContext(conf);

​​// 在java中,创建共享变量,就是调用SparkContext的broadcast()方法
​​// 获取的返回结果是Broadcast类型
​​final int factor = 3;

​​final Broadcast factorBroadcast = sc.broadcast(factor);

​​List numberList = Arrays.asList(1, 2, 3, 4, 5);

​​JavaRDD numbers = sc.parallelize(numberList);

​​// 让集合中的每个数字,都乘以外部定义的那个factor
​​JavaRDD multipleNumbers = numbers.map(new Function() {

​​​private static final long serialVersionUID = 1L;

​​​@Override
​​​public Integer call(Integer v1) throws Exception {
​​​​// 使用共享变量时,调用其value()方法,即可获取其内部封装的值
​​​​int factor = factorBroadcast.value();
​​​​return v1 * factor;
​​​}
​​});

multipleNumbers.foreach(new VoidFunction() {

private static final long serialVersionUID = 1L;

@Override
​​​public void call(Integer t) throws Exception {
​​​​System.out.println(t);  
​​​}
​​});

sc.close();
}
}

Scala版本案例

object BroadcastVariable {

def main(args: Array[String]){

val conf = new SparkConf().setAppName("name").setMaster("local")

val sc = new SparkContext(conf)

val factor = 3

val factorBroadcast = sc.broadcast(factor)

val numberArray = Array(1,2,3,4,5)

val numbers = sc.parallelize(numberArray, 1)

val multipleNumbers = numbers.map { num => num * factorBroadcast.value }

multipleNumbers.foreach { num => println(num) }
}
}

你可能感兴趣的:(Broadcast Variable)