Spark-submit 提交jar包执行WordCount功能
1. word.txt文件内容
hello world
hello kb09
hello hehe
在hdfs上新建kb09file2文件夹
hdfs dfs -mkdir /kb09file2
将word.txt上传到hdfs
hdfs dfs -put word.txt /kb09file2
2. MAVEN依赖
创建maven工程过程可以参考我这篇博客:
Maven工程实现Spark api—wordcount和打印hdfs文件(非常详细的maven工程创建过程以及不显示日志打印)
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.8</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
3. properties文件创建
1.新建resource文件夹
2.右击resource文件夹 --> 选择Mark Directory as --> Sources Root
3.右击resource文件夹 --> new --> file --> 文件名:userset.properties
4.文件内容:
//需要加载文件所在的hdfs上的路径
loadPath:hdfs://192.168.116.60:9000/kb09file2/word.txt
//输出结果文件保存在hdfs上的路径
outPath:hdfs://192.168.116.60:9000/kb09file2/output
右击 userset.properties --> Show in Explorer
打开userset.properties文件所在路径,传到Linux 的 /kb09file2 文件夹下
4. Scala代码
import java.io.FileInputStream
import java.util.Properties
import org.apache.spark.{SparkConf, SparkContext}
object WordCount {
def main(args: Array[String]): Unit = {
//scala代码实现spark入口
val conf = new SparkConf().setMaster("local[*]").setAppName("WordCount")
val sc = new SparkContext(conf)
//使用Properties方法
val properties = new Properties()
//properties文件所在Linux的路径
properties.load(new FileInputStream("/kb09file2/userset.properties"))
//路径要toString
val loadFile = properties.get("loadPath").toString
val outFilePath = properties.get("outPath").toString
//加载hdfs文件到SparkRDD
val lines = sc.textFile(loadFile)
//WordCount实现
val result = lines.flatMap(x=>x.split(" ")).map((_,1)).reduceByKey(_+_)
//结果打印
result.collect.foreach(println)
//结果保存在hdfs
result.saveAsTextFile(outFilePath)
sc.stop()
}
}
5. 打jar包过程
右击 --> Show in Explorer
6. 删除安全保护文件
使用压缩软件打开jar文件
打开META-INF文件夹
删除如下框选文件
将jar包文件上传到Linux的 /kb09file2 文件夹下
7. 开启Spark
./opt/spark245/sbin/start-all.sh
8. 执行jar包
cd /kb09file2
spark-submit --class WordCount --master local[*] ./WordCountTest.jar
9. 结果
在 hdfs上 查看结果文件