1. 程式人生 > >python、scala、java分別實現在spark上實現WordCount

python、scala、java分別實現在spark上實現WordCount

下面分別貼出python、scala、java版本的wordcount程式:

python版:

import logging
from operator import add
from pyspark import SparkContext
logging.basicConfig(format='%(message)s', level=logging.INFO)

#import local file
test_file_name = "file:///home/yq/worldcount.py"
#此時spark-out目錄不要建立,會自動生成
out_file_name = "file:///home/yq/spark-out"

sc = SparkContext("local","wordcount app")

# text_file rdd object
text_file = sc.textFile(test_file_name)

# counts
counts = text_file.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b)
counts.saveAsTextFile(out_file_name)
java版:

這裡需要說的是,這裡的輸入為監聽hadoop1機器上的一個9999埠的內容,其他的沒區別

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.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import scala.Tuple2;

public class WordCount {

	public static void main(String[] args) throws InterruptedException {
		SparkConf conf = new SparkConf().setAppName("wordcount").setMaster("local[2]");
		// 建立該物件就類似於Spark Core中的JavaSparkContext,類似於Spark SQL中的SQLContext
		// 該物件除了接受SparkConf物件,還要接受一個Batch Interval引數,就是說,每收集多長時間資料劃分一個batch去進行處理
		// 這裡我們看Durations裡面可以設定分鐘、毫秒、秒,這裡設定一秒
		JavaStreamingContext jssc = new JavaStreamingContext(conf,Durations.seconds(10));
		
		// 首先建立輸入DStream,代表一個數據源比如從socket或kafka來持續不斷的進入實時資料流
		// 建立一個監聽埠的socket資料流,這裡面就會有每隔一秒生成一個RDD,RDD的元素型別為String就是一行一行的文字
		JavaReceiverInputDStream<String> lines = jssc.socketTextStream("hadoop1", 9999);
		// 接著Spark Core提供的運算元直接應用在DStream上即可,運算元底層會應用在裡面的每個RDD上面,RDD轉換後的新RDD會作為新DStream中RDD
		JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>(){

			private static final long serialVersionUID = 1L;

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

			private static final long serialVersionUID = 1L;

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

			private static final long serialVersionUID = 1L;

			@Override
			public Integer call(Integer v1, Integer v2) throws Exception {
				return v1 + v2;
			}
			
		});
		
		// 最後每次計算完,都列印一下這一秒鐘的單詞計數情況,並休眠5秒鐘,以便於我們測試和觀察
		wordcounts.print();
		
		// 必須呼叫start方法,整個spark streaming應用才會啟動執行,然後卡在那裡,最後close釋放資源
		jssc.start();
		jssc.awaitTermination();
		jssc.close();
	}
}

scala版:
package com.hq

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
 
 /**
  * 統計字元出現次數
  */
object WordCount {
  def main(args: Array[String]) {
     if (args.length < 1) {
       System.err.println("Usage: <file>")
       System.exit(1)
     }
 
     val conf = new SparkConf()
     val sc = new SparkContext(conf)
     val line = sc.textFile(args(0))
 
     line.flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).collect().foreach(println)
 
     sc.stop()
   }
}


   關於提交程式 在spark目錄下,進入bin目錄下執行 ./spark-submit  /usr/*/wordcount.py 其他的程式提交方式類似 如果需要設定一些引數的話 可以通過./spark-submit --help 檢視引數選項 自己選擇 

 首先test-data.txt的內容為:

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

下面提交一下程式來看看結果: