spark與kafaka整合workcount示例 spark-stream-kafka

hgs19921112發表於2018-10-19
package hgs.spark.streaming
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.Seconds
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.storage.StorageLevel
import kafka.serializer.StringDecoder
import org.apache.kafka.common.serialization.StringDeserializer
import kafka.serializer.DefaultDecoder
import org.apache.spark.HashPartitioner
/*		
 * pom.xml新增
 * <dependency>
   			 <groupId>org.apache.spark</groupId>
    		 <artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
    		 <version>2.1.1</version>
		</dependency>
		
* */
object SparkStreamingKafkaReciverWordCount {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("KafkaWordCount").setMaster("local[2]")
    val sc = new SparkContext(conf)
    val ssc = new StreamingContext(sc,Seconds(4)) 
    ssc.checkpoint("d:\\checkpoint")
    
    val updateFunc=(iter:Iterator[(String,Seq[Int],Option[Int])])=>{
    //iter.flatMap(it=>Some(it._2.sum+it._3.getOrElse(0)).map((it._1,_)))//方式一
    //iter.flatMap{case(x,y,z)=>{Some(y.sum+z.getOrElse(0)).map((x,_))}}//方式二
    iter.flatMap(it=>Some(it._1,(it._2.sum.toInt+it._3.getOrElse(0))))//方式三
    }
    //注意下面的map一定要加上泛型,否則createStream會報錯
    //kafaka的一些引數
    val props = Map[String,String](
             "bootstrap.servers"->"bigdata01:9092,bigdata02:9092,bigdata03:9092",
             "group.id"->"group_test",
             "enable.auto.commit"->"true",
             "auto.commit.intervals.ms"->"2000",
             "auto.offset.reset"->"smallest",
             "zookeeper.connect"->"bigdata01:2181,bigdata02:2181,bigdata03:2181")
    //topics
    val topics = Map[String,Int]("test"->1)
    
    val rds = KafkaUtils.createStream[String,String,StringDecoder,StringDecoder](ssc, props, topics, StorageLevel.MEMORY_AND_DISK)
    
    val words = rds.flatMap(x=>x._2.split(" "))
    val wordscount = words.map((_,1)).updateStateByKey(updateFunc, new HashPartitioner(sc.defaultMinPartitions), true)
    
    wordscount.print()
    //啟動
    ssc.start()
    ssc.awaitTermination()
    
  }
}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31506529/viewspace-2216851/,如需轉載,請註明出處,否則將追究法律責任。

相關文章