【Spark篇】---Spark中广播变量和累加器

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端更新。

相关文章
相关标签/搜索