选择在idea中创建与运行
指定了虚拟机与端口
package com.uu
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
object SparkStreaming1 {
def main(args: Array[String]): Unit = {
//stream模式至少有两个进程local[2]
val conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount")
//设置执行的时间间隔
val ssc = new StreamingContext(conf, Seconds(20))
//创建DStream ,连接到某个主机的某个端口上面
val lines = ssc.socketTextStream("hadoop101", 9999)
// 将每一行切分为单词
val words = lines.flatMap(_.split(" "))
// 统计单词的个数
val pairs = words.map(word => (word, 1))
val wordCounts = pairs.reduceByKey(_ + _)
// 每组打印前十个数字
wordCounts.print()
ssc.start() // 开启
ssc.awaitTermination() // 等待计算停止
}
}
在虚拟机端
用nc来模拟发送
nc -l 9999