● 编写java代码
package com.ws.spark;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;
import java.util.Arrays;
import java.util.Iterator;
/**
* @author Jun
* data 2018-09-29 9:24
* 使用java实现spark单词计数
*/
public class JavaWordCount {
public static void main(String[] args) {
//创建配置
SparkConf conf = new SparkConf();
//创建context对象
JavaSparkContext context = new JavaSparkContext(conf);
//读取文件 可以是本地文件或者HDFS路径
JavaRDD<String> javaRDD = context.textFile(args[0]);
//压平,切单词
JavaRDD<String> flatMap = javaRDD.flatMap(new FlatMapFunction<String, String>() {
@Override
public Iterator<String> call(String s) throws Exception {
//切单词
String[] split = s.split(" ");
return Arrays.asList(split).iterator();
}
});
//单词次数加一
JavaPairRDD<String, Integer> javaPairRDD = flatMap.mapToPair(new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String s) throws Exception {
return new Tuple2<>(s, 1);
}
});
//聚合,将每个单词出现数量相加
JavaPairRDD<String, Integer> reduceByKey = javaPairRDD.reduceByKey(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer integer, Integer integer2) throws Exception {
return integer + integer2;
}
});
//只能根据key排序,所以需要将元组位置交换, (单词,出现数量)->(出现数量,单词)
JavaPairRDD<Integer, String> mapToPair = reduceByKey.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() {
@Override
public Tuple2<Integer, String> call(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
return stringIntegerTuple2.swap();//元组位置交换
}
});
//排序 根据key排序
JavaPairRDD<Integer, String> reduce = mapToPair.sortByKey(false);
//保存
reduce.saveAsTextFile(args[1]);
}
}
●使用idea 的maven打包 上传至Linux
●linux运行程序命令:
[root@hadoop-01 ~]# ./apps/spark-2.2.0/bin/spark-submit --master spark://hadoop-01:7077 --class com.ws.spark.JavaWordCount /root/javaSparkWordCount.jar hdfs://hadoop-01:9000/test.txt hdfs://hadoop-01:9000/testlog
●注意 :
若使用linux local文件的话,确保每个节点上都拥有文件,否则报文件不存在错误;
本命令使用hdfs路径,避免该错误;