Spark(RDDS概念、Action、Transformation、练习题)
一、为什么使用spark?
1、MapReduce编程模型的局限性
繁杂
(1)只有Map和Reduce两个操作,复杂的逻辑需要大量的样板代码
处理效率低:
(1)Map中间结果写磁盘,Reduce写HDFS,多个Map通过HDFS交换数据
(2)任务调度与启动开销大
不适合迭代处理、交互式处理和流式处理
2、Spark是类Hadoop MapReduce的通用并行框架
(1)Job中间输出结果可以保存在内存,不再需要读写HDFS
(2)比MapReduce平均快10倍以上
二、Spark简介
诞生于加州大学伯克利分校AMP实验室,是一个基于内存的分布式计算框架
发展历程
2009年诞生于加州大学伯克利分校AMP实验室2010年正式开源
2013年6月正式成为Apache孵化项目2014年2月成为Apache顶级项目2014年5月正式发布Spark 1.0版本
2014年10月Spark打破MapReduce保持的排序记录
2015年发布了1.3、1.4、1.5版本
2016年发布了1.6、2.x版本
三、Spark优势
速度快
基于内存数据处理,比MR快100个数量级以上(逻辑回归算法测试)基于硬盘数据处理,比MR快10个数量级以上
易用性
支持Java、Scala、Python、R语言交互式shell方便开发测试
通用性
一栈式解决方案:批处理、交互式查询、实时流处理、图计算及机器学习
多种运行模式
YARN、Mesos、EC2、Kubernetes、Standalone、Local
四、Spark技术栈
Spark Core
核心组件,分布式计算引擎
Spark SQL
高性能的基于Hadoop的SQL解决方案
Spark Streaming
可以实现高吞吐量、具备容错机制的准实时流处理系统
Spark Graphx
分布式图处理框架
Spark MLlib
构建在Spark上的分布式机器学习库
五、Spark初体验
spark-shell: Spark自带的交互式工具
本机
spark-shell --master local[*]
Standalone
spark-shell --master spark://MASTERHOST:7077
YARN
spark-shell --master yarn-client
六、Spark架构核心组件
术语 | 说明 |
---|---|
Application | 建立在Spark上的用户程序,包括Driver代码和运行在集群各节点Executor中的代码 |
Driver program | 驱动程序,Application中的main函数并创建SparkContext |
Cluster Manager | 在集群(Standalone,Mesos,Yarn)上获取资源的外部服务 |
Worker Node | 集群中任何可以运行Application代码的节点 |
Executor | 某个Application运行在worker节点上的一个进程 |
Task | 被送到某个Executor上的工作单元 |
Job | 包含多个Task组成的并行计算,往往由Spark Action触发生成,一个Application中往往会产生多个job |
Stage | 每个Job会被拆分成多组Task,作为一个TaskSet,其名称位Stage |
七、使用Idea初始化Spark运行环境
7.1 创建maven工程
7.2 下载依赖包:
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
7.3 添加Scala SDK
7.5 添加log4j.properties
在resources中创建log4j.properties,并将下面内容添加进去:
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Set everything to be logged to the console
log4j.rootCategory=ERROR, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{
yy/MM/dd HH:mm:ss} %p %c