1. 程式人生 > >spark實時計算kafka訊息佇列中的wordcount

spark實時計算kafka訊息佇列中的wordcount

package sparkTestJava;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import kafka.serializer.StringDecoder;

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

import scala.Tuple2;

public class KafkaDirectWordCount {

	public static void main(String[] args) {
		SparkConf conf = new SparkConf().setAppName("wordcount").setMaster("local[2]");
		JavaStreamingContext jssc = new JavaStreamingContext(conf,Durations.seconds(5));
		
		// 首先要建立一份kafka引數map
		Map<String, String> kafkaParams = new HashMap<String, String>();
		// 我們這裡是不需要zookeeper節點的啊,所以我們這裡放broker.list
		kafkaParams.put("metadata.broker.list", 
				"192.168.*.*:9092,192.168.*.*:9092,192.168.*.*:9092");
		
		// 然後建立一個set,裡面放入你要讀取的Topic,這個就是我們所說的,它給你做的很好,可以並行讀取多個topic
		Set<String> topics = new HashSet<String>();
		topics.add("wordcount20170605");
		
		JavaPairInputDStream<String,String> lines = KafkaUtils.createDirectStream(
				jssc, 
				String.class, // key型別
				String.class, // value型別
				StringDecoder.class, // 解碼器
				StringDecoder.class,
				kafkaParams, 
				topics);
		
		JavaDStream<String> words = lines.flatMap(new FlatMapFunction<Tuple2<String,String>, String>(){

			private static final long serialVersionUID = 1L;

			@Override
			public Iterable<String> call(Tuple2<String,String> tuple) throws Exception {
			 	return Arrays.asList(tuple._2.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;
			}
			
		});
		
		wordcounts.print();
		
		jssc.start();
		jssc.awaitTermination();
		jssc.close();
	}
}

首先在執行程式之前得在kafka中建立一個名為wordcount20170605的topic 

  接著利用hadoop:9092,hadoop1:9092,hadoop2:9092埠來向topic中產生資料,然後程式收集這些資料之後並進行實時的計算

執行截圖: