2.1 创建 Maven 项目

增加 Scala 插件

Spark 版本为 3.0.0,默认采用的 Scala 编译版本为 2.12
image.png

增加依赖关系

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.apache.spark</groupId>
  4. <artifactId>spark-core_2.12</artifactId>
  5. <version>3.0.0</version>
  6. </dependency>
  7. </dependencies>
  8. <build>
  9. <plugins>
  10. <!-- 该插件用于将 Scala 代码编译成 class 文件 -->
  11. <plugin>
  12. <groupId>net.alchim31.maven</groupId>
  13. <artifactId>scala-maven-plugin</artifactId>
  14. <version>3.2.2</version>
  15. <executions>
  16. <execution>
  17. <!-- 声明绑定到 maven compile 阶段 -->
  18. <goals>
  19. <goal>testCompile</goal>
  20. </goals>
  21. </execution>
  22. </executions>
  23. </plugin>
  24. <plugin>
  25. <groupId>org.apache.maven.plugins</groupId>
  26. <artifactId>maven-assembly-plugin</artifactId>
  27. <version>3.1.0</version>
  28. <configuration>
  29. <descriptorRefs>
  30. <descriptorRef>jar-with-dependencies</descriptorRef>
  31. </descriptorRefs>
  32. </configuration>
  33. <executions>
  34. <execution>
  35. <id>make-assembly</id>
  36. <phase>package</phase>
  37. <goals>
  38. <goal>single</goal>
  39. </goals>
  40. </execution>
  41. </executions>
  42. </plugin>
  43. </plugins>
  44. </build>

WordCount

  1. import org.apache.spark.rdd.RDD
  2. import org.apache.spark.{SparkConf, SparkContext}
  3. object WordCount {
  4. def main(args: Array[String]): Unit = {
  5. // 创建Spark运行配置对象
  6. val sparkConf = new SparkConf().setMaster("local[*]").setAppName("WordCount")
  7. // 创建Spark上下文环境对象(连接对象)
  8. val sc: SparkContext = new SparkContext(sparkConf)
  9. // 读取文件数据
  10. val fileRDD: RDD[String] = sc.textFile("F:\\学习资料下载\\spark\\2.资料\\data\\WordCount.txt")
  11. // 将文件中的数据进行分词
  12. val wordRDD: RDD[String] = fileRDD.flatMap(_.split(" "))
  13. // 转换数据结构 word => (word, 1)
  14. val word2OneRDD: RDD[(String, Int)] = wordRDD.map((_, 1))
  15. // 将转换结构后的数据按照相同的单词进行分组聚合
  16. val word2CountRDD: RDD[(String, Int)] = word2OneRDD.reduceByKey(_ + _)
  17. // 将数据聚合结果采集到内存中
  18. val word2Count: Array[(String, Int)] = word2CountRDD.collect()
  19. // 打印结果
  20. word2Count.foreach(println)
  21. //关闭 Spark 连接
  22. sc.stop()
  23. }

image.png