Spark-Shell交互式客户端

Spark WordCount 实战
本文详细介绍了如何使用Apache Spark执行WordCount程序,包括启动交互Shell、编写Scala代码、配置Maven依赖、打包并提交到集群运行的全过程。涵盖Spark Shell命令、RDD操作、Maven配置及集群提交方式。

启动交互shell

[root@hdp-1 bin]# ./spark-shell --master spark://hdp-2:7077 --executor-memory 500m --total-executor-cores 1

--master spark://hdp-2:7077  sparkmaster节点的地址

--executor-memory 500m 

--total-executor-cores 1 

运行wordcount程序

sc.textFile("/spark/hi.txt").flatMap(_.split(",")).map((_,1)).reduceByKey(_+_).saveAsTextFile("/spark/out")

textFile("/spark/hi.txt")是hdfs中读取数据

flatMap(_.split(" "))先map再压平

map((_,1))将单词和1构成元组

reduceByKey(_+_)按照key进行reduce,并将value累加

saveAsTextFile("/spark/out")将结果写入到hdfs中

提交到yarn集群上运行

spark-shell --master yarn --deploy-mode client

scala> val array = Array(1,2,3,4,5)

array: Array[Int] = Array(1, 2, 3, 4, 5)

scala> val rdd = sc.makeRDD(array)

rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[0] at makeRDD at <console>:26

scala> rdd.count

res0: Long = 5   

scala编写WordCount程序打包到集群上运行

1.依赖

<properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <scala.version>2.11.8</scala.version>
        <spark.version>2.2.0</spark.version>
        <hadoop.version>2.6.5</hadoop.version>
        <encoding>UTF-8</encoding>
    </properties>

    <dependencies>
        <!-- 导入scala的依赖 -->
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>

        <!-- 导入spark的依赖 -->
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>

        <!-- 指定hadoop-client API的版本 -->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>${hadoop.version}</version>
        </dependency>

    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <!-- 编译scala的插件 -->
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>scala-maven-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <!-- 编译java的插件 -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.5.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>add-source</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>


            <!-- 打jar插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

2.代码

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}


object ScalaWordCount {

  def main(args: Array[String]): Unit = {
    //创建spark配置,设置应用程序名字
    //val conf = new SparkConf().setAppName("ScalaWordCount")
    val conf = new SparkConf().setAppName("ScalaWordCount").setMaster("local[4]")
    //创建spark执行的入口
    val sc = new SparkContext(conf)
    //指定以后从哪里读取数据创建RDD(弹性分布式数据集)
    //sc.textFile(args(0)).flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).sortBy(_._2, false).saveAsTextFile(args(1))

    val lines: RDD[String] = sc.textFile(args(0))
    //切分压平 _代表一行内容
    val words: RDD[String] = lines.flatMap(_.split(","))
    //将单词和一组合,形成一个元组
    val wordAndOne: RDD[(String, Int)] = words.map((_, 1))
    //按key进行聚合
    val reduced:RDD[(String, Int)] = wordAndOne.reduceByKey(_+_)
    //排序
    val sorted: RDD[(String, Int)] = reduced.sortBy(_._2, false)
    //将结果保存到HDFS中
    sorted.saveAsTextFile(args(1))
    //释放资源
    sc.stop()

  }

3、打成jar包提交到集群运行

./spark-submit --master spark://hdp-1:7077 --class com.zpark.wc.ScalaWordCount /root/apps/original-sparkwctwo-1.0-SNAPSHOT.jar hdfs://hdp-1:9000/spark/hi.txt hdfs://hdp-1:9000/spark/out
 

### Spark-Shell 连接 Spark 集群的方法及原理 #### 方法概述 `spark-shell` 是一种交互式的 Scala 或 Python 环境,用于快速测试和运行 Spark 应用程序。它可以通过指定参数连接到不同的集群管理器(如 YARN、Mesos 或 Standalone)。以下是通过 `spark-shell` 连接到 Spark 集群的具体方法及其含义。 #### 参数配置 要使 `spark-shell` 连接到 Spark 集群,通常需要设置以下关键参数: 1. **--master**: 指定集群管理器的 URL。例如,对于 YARN 集群模式,可以使用 `yarn`;对于独立模式,则可使用 `spark://<master-host>:<port>`。 示例命令如下: ```bash ./bin/spark-shell --master yarn --deploy-mode client ``` 2. **--deploy-mode**: 定义驱动程序的位置。可以选择两种模式: - `client`: 驱动程序在提交作业的工作站上运行。 - `cluster`: 驱动程序在工作节点之一上运行。 3. **其他常见参数**: - `--num-executors`: 设置执行器的数量。 - `--executor-memory`: 设置每个执行器的内存大小。 - `--driver-memory`: 设置驱动程序的内存大小。 - `--conf`: 添加自定义配置项。 这些参数允许用户灵活调整资源分配并优化性能[^1]。 #### 原理解析 当启动带有上述参数的 `spark-shell` 时,会发生以下几个主要过程: 1. **初始化上下文**: 创建一个名为 `sc` 的全局变量,表示 SparkContext 实例。这是与 Spark 集群通信的核心对象。 2. **连接至 Master 节点**: 根据 `--master` 参数中的地址,尝试建立与集群管理器的联系。 3. **部署模式选择**: - 如果采用客户端模式 (`client`),则本地机器上的 JVM 将作为驱动程序运行环境,并向远程 Worker 发送任务请求。 - 若为集群模式 (`cluster`),驱动程序会被调度到某个 Work 节点上运行,而 CLI 工具仅负责监控日志输出。 4. **资源配置传递**: 所有额外设定好的选项都会被发送给 ResourceManager 来安排实际计算所需的硬件规格[^3]。 因此,在日常开发调试阶段推荐使用 Client Mode 方便查看即时反馈;而在生产环境中更倾向于 Cluster Mode 提升稳定性与隔离度[^2]。 ```scala // 在 spark-shell 中访问 sc 对象来验证是否成功连入集群 println(sc.master) // 输出当前使用的 master 地址 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值