广播变量在最后补充。
今天的示例主要介绍一下累加器的使用。Spark官方文档的Action介绍中有提到 foreach
foreach(func):Run a function func on each element of the dataset. This is usually done for side effects such as updating an Accumulator or interacting with external storage systems.
Note: modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closuresfor more details.
意思是说,调用foreach函数可以遍历rdd中的每一个元素,但是在foreach外部,不可以更新累加器以外的变量,否则会出现与期望值不符的结果。
例如,你想做一个简单求和计数,首先声明一个变量,然后在foreach内部增值。请注意,这样是行不通的。
官方文档中这样介绍:By default, when Spark runs a function in parallel as a set of tasks on different nodes, it ships a copy of each variable used in the function to each task. 默认情况下,当Spark以不同节点上的一组任务并行运行一个函数时,它会将该函数中使用的每个变量的副本发送给每个任务。
为了解决这个问题,除了之前示例中用过的reduce函数外,还可以引入累加器。
package c