SparkStreaming实现HDFS的wordCount(java版)

           利用sparkstreaming实现hdfs文件系统中的某个目录下的wordcount

代码如下:

package sparkTestJava;

import java.util.Arrays;

import org.apache.spark.SparkConf;
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 org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import scala.Tuple2;

public class HDFSWordCount {

	public static void main(String[] args) {
		SparkConf conf = new SparkConf().setAppName("wordcount").setMaster("local[2]");
		JavaStreamingContext jssc = new JavaStreamingContext(conf,Durations.seconds(5));
		
		JavaDStream lines = jssc.textFileStream("hdfs://hadoop:9000/sparkTest");
		
		JavaDStream words = lines.flatMap(new FlatMapFunction(){

			private static final long serialVersionUID = 1L;

			@Override
			public Iterable call(String line) throws Exception {
			 	return Arrays.asList(line.split(" "));
			}
			
		});
		
		JavaPairDStream pairs = words.mapToPair(new PairFunction(){

			private static final long serialVersionUID = 1L;

			@Override
			public Tuple2 call(String word) throws Exception {
				return new Tuple2(word, 1);
			}
			
		});
		
		JavaPairDStream wordcounts = pairs.reduceByKey(new Function2(){

			private static final long serialVersionUID = 1L;

			@Override
			public Integer call(Integer v1, Integer v2) throws Exception {
				return v1 + v2;
			}
			
		});
		
		wordcounts.print();
		
		jssc.start();
		jssc.awaitTermination();
		jssc.stop();
		jssc.close();
	}
}


在运行程序前先启动hdfs,spark,这里不再赘述

test-data.txt的内容为:

hadoop hadoop
hadoop1 hadoop1 hadoop1
hadoop2 hadoop2 hadoop2 hadoop2
hadoop3
spark spark
spark
spark1

先运行程序,然后再将测试文件test-data.txt传到hdfs中的对应的sparkTest目录下,这是可以看到结果如下:SparkStreaming实现HDFS的wordCount(java版)_第1张图片

你可能感兴趣的:(Spark)