累加器:分布式共享只写变量。(Executor和Executor之间不能读数据)。
累加器用来把Executor端变量信息聚合到Driver端。在Driver中定义的一个变量,在Executor端的每个task都会得到这个变量的一份新的副本,每个task更新这些副本的值后,传回Driver端进行合并计算。
1)累加器使用
(1)累加器定义(SparkContext.accumulator(initialValue)方法)
LongAccumulator longAccumulator = JavaSparkContext.toSparkContext(sc).longAccumulator();
(2)累加器添加数据(累加器.add方法)
longAccumulator.add(stringIntegerTuple2._2);
(3)累加器获取数据(累加器.value)
longAccumulator.value()
// 转换为scala的累加器
LongAccumulator longAccumulator = JavaSparkContext.toSparkContext(sc).longAccumulator();
// 在foreach中使用累加器
tupleRDD.foreach(new VoidFunction<Tuple2<String, Integer>>() {
@Override
public void call(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
longAccumulator.add(stringIntegerTuple2._2);
// 不要在executor端获取累加器的值,因为不准确 因此我们说累加器叫分布式共享只写变量
System.out.println(longAccumulator.value());
}
});
System.out.println(longAccumulator.value());