当前位置:网站首页>Spark累加器和廣播變量
Spark累加器和廣播變量
2022-06-24 06:59:00 【Angryshark_128】
累加器
累加器有些類似Redis的計數器,但要比計數器强大,不僅可以用於計數,還可以用來累加求和、累加合並元素等。
假設我們有一個word.txt文本,我們想要統計該文本中單詞“sheep”的行數,我們可以直接讀取文本filter過濾然後計數。
sc.textFile("word.txt").filter(_.contains("sheep")).count()
假設我們想分別統計文本中單詞"sheep""wolf"的行數,如果按照上述方法需要計算兩次
sc.textFile("word.txt").filter(_.contains("sheep")).count()
sc.textFile("word.txt").filter(_.contains("wolf")).count()
如果要分別統計100個單詞的行數,則要計算100次
如果使用累加器,則只需要讀一次即可
val count1=sc.acccumlator(0)
val count2=sc.acccumlator(0)
...
def processLine(line:String):Unit{
if(line.contains("sheep")){
count1+=1
}
if(line.contains("wolf")){
count2+=1
}
...
}
sc.textFile("word.txt").foreach(processLine(_))
不僅Int類型可以累加,Long、Double、Collection也可以累加,還可以進行自定義,而且這個變量可以在Spark的WebUI界面看到。
注意:累加器只能在Driver端定義和讀取,不能在Executor端讀取。
廣播變量
廣播變量允許緩存一個只讀的變量在每臺機器(worker)上面,而不是每個任務(task)保存一份備份。利用廣播變量能够以一種更有效率的方式將一個大數據量輸入集合的副本分配給每個節點。
廣播變量通過兩個方面提高數據共享效率:
(1)集群中每個節點(物理機器)只有一個副本,默認的閉包是每個任務一個副本;
(2)廣播傳輸是通過BT下載模式實現的,也就是P2P下載,在集群多的情况下,可以極大地提高數據傳輸速率。廣播變量修改後,不會反饋到其他節點。
val list=sc.parallize(0 to 10)
val brdList=sc.broadcast(list)
sc.textFile("test.txt").filter(brdList.value.contains(_.toInt)).foreach(println)
使用時,需注意:
(1)適用於小變量分發,對於動則幾十M的變量,每個任務都發送一次既消耗內存,也浪費時間
(2)廣播變量只能在driver端定義,在Executor端讀取,Executor不能修改
边栏推荐
- 35 year old crisis? It has become a synonym for programmers
- Command ‘[‘where‘, ‘cl‘]‘ returned non-zero exit status 1.
- "Adobe international certification" in the design industry, why can't big but big designs have good results?
- 开源与创新
- Koa source code analysis
- LuChen technology was invited to join NVIDIA startup acceleration program
- Papamelon 11 number of calculation permutation [combinatorics]
- Come on, it's not easy for big factories to do projects!
- 【问题解决】虚拟机配置静态ip
- Laravel文档阅读笔记-Laravel Str slug() Function Example
猜你喜欢
随机推荐
Code scanning | a sharp tool for controlling code quality
leetcode:剑指 Offer 26:判断t1中是否含有t2的全部拓扑结构
Use of SQL join
云监控系统 HertzBeat v1.1.0 发布,一条命令开启监控之旅!
On BOM and DOM (2): DOM node hierarchy / attributes / Selectors / node relationships / detailed operation
十年
项目Demo
Application of intelligent reservoir management based on 3D GIS system
Come on, it's not easy for big factories to do projects!
C language student management system - can check the legitimacy of user input, two-way leading circular linked list
sql join的使用
华为云低时延技术的九大绝招
About Stacked Generalization
Laravel文档阅读笔记-Laravel Str slug() Function Example
雲監控系統 HertzBeat v1.1.0 發布,一條命令開啟監控之旅!
机器人迷雾之算力与智能
Challenges brought by maker education to teacher development
数据库 存储过程 begin end
setInterval里面的函数不能有括号
leetcode:1856. 子数组最小乘积的最大值

![[binary tree] - middle order traversal of binary tree](/img/93/442bdbecb123991dbfbd1e5ecc9d64.png)







