1、前述java
Spark中由於算子中的真正邏輯是發送到Executor中去運行的,因此當Executor中須要引用外部變量時,須要使用廣播變量。apache
累機器至關於統籌大變量,經常使用於計數,統計。api
2、具體原理ide
一、廣播變量spa
一、能不能將一個RDD使用廣播變量廣播出去?scala
不能,由於RDD是不存儲數據的。能夠將RDD的結果廣播出去。code
二、 廣播變量只能在Driver端定義,不能在Executor端定義。blog
三、 在Driver端能夠修改廣播變量的值,在Executor端沒法修改廣播變量的值。it
四、若是executor端用到了Driver的變量,若是不使用廣播變量在Executor有多少task就有多少Driver端的變量副本。spark
五、若是Executor端用到了Driver的變量,若是使用廣播變量在每一個Executor中只有一份Driver端的變量副本。
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()
二、累加器
Scala代碼:
import org.apache.spark.{SparkConf, SparkContext} object AccumulatorOperator { def main(args: Array[String]): Unit = { val conf = new SparkConf() conf.setMaster("local").setAppName("accumulator") val sc = new SparkContext(conf) val accumulator = sc.accumulator(0) sc.textFile("./records.txt",2).foreach {//兩個變量 x =>{accumulator.add(1) println(accumulator)}} println(accumulator.value) sc.stop() } }
java代碼:
package com.spark.spark.others; import org.apache.spark.Accumulator; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.VoidFunction; /** * 累加器在Driver端定義賦初始值和讀取,在Executor端累加。 * @author root * */ public class AccumulatorOperator { public static void main(String[] args) { SparkConf conf = new SparkConf(); conf.setMaster("local").setAppName("accumulator"); JavaSparkContext sc = new JavaSparkContext(conf); final Accumulator<Integer> accumulator = sc.accumulator(0); // accumulator.setValue(1000); sc.textFile("./words.txt",2).foreach(new VoidFunction<String>() { /** * */ private static final long serialVersionUID = 1L; @Override public void call(String t) throws Exception { accumulator.add(1); // System.out.println(accumulator.value()); System.out.println(accumulator); } }); System.out.println(accumulator.value()); sc.stop(); } }
結果:
累加器在Driver端定義賦初始值,累加器只能在Driver端讀取最後的值,在Excutor端更新。