1.环境准备
虚拟机:vmware workstation16
linux版本:centOS 7
linux 分布式环境:hadoop 3.1.1,spark 2.4.0 scala 2.11.8
编辑器:JetBrains idea 2022
首先要启动hadoop和spark,如果没有安装,请先安装并配置
2.编写Scala程序实现
打开我们的idea编辑器,创建Scala项目
写入我们的代码
package com.ldu
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.FileSystem
import org.apache.spark.{SparkConf, SparkContext}
object max_wangchen {
def main(args: Array[String]): Unit = {
// 创建一个Scala版本的Spark Context
val conf = new SparkConf().setAppName("maxvalue6564").setMaster("local")
val sc = new SparkContext(conf)
val h_conf = sc.hadoopConfiguration
h_conf.set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName)
h_conf.set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName)
sc.setLogLevel("ERROR")
val lines = sc.textFile("hdfs://master6564:9000/wordcount/word.txt").filter(_.trim().length>0).map(line => ("key",line.trim.toInt)).groupByKey().map(x =>{
var min = Integer.MAX_VALUE
var max = Integer.MIN_VALUE
for(num<- x._2){
if(num > max) {
max = num
}
if(num < min) {
min = num
}
}
(max,min)
})
lines.saveAsTextFile("hdfs://master6564:9000/wordcount/result2")
}
}
注意这里的hdfs地址要改为自己的
输入数据展示(word.txt)
然后上传到hadoop中
# hadoop fs -put word.txt /wordcount
3.项目打包
这里我们使用idea的maven自动打包工具,步骤如下
点击右侧maven
先进行clean
然后编译
最后进行打jar包
完成后,我们会在target中,找到我们刚刚打的jar包
4.在spark中运行jar包
在centos终端中执行以下命令
[root@master6564 spark]# spark-submit --class com.ldu.max_wangchen --master yarn /home/master6564/workspace4/wordcount/target/wordcount-1.0-SNAPSHOT.jar
运行成功
运行命令,查看hdfs中的结果
[root@master6564 bin]# hdfs dfs -text /wordcount/result2/part*
结果: