如果是单机版spark-shell,程序无需改动。
由于在CDH环境下,localhost应该换为master的hostname。
确保安装好CDH,并运行良好,某在master节点练习spark。
## Spark streaming 第一个例子练习:
在一台终端A下:nc -lk 9999
(确保此端口没有被占用, 查看端口占用情况: lsof -i: 9999 )
在另一个终端B:spark-shell 进入scala的console:
import org.apache.spark.streaming._
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.api.java.function._
import org.apache.spark.streaming._
import org.apache.spark.streaming.api._
// Create a StreamingContext with a local master
val ssc = new StreamingContext(sc, Seconds(1))
// Create a DStream that will connect to serverIP:serverPort, like localhost:9999
val lines = ssc.socketTextStream("master", 9999)
// Split each line into words
val words = lines.flatMap(_.split(" "))
import org.apache.spark.streaming.StreamingContext._
// Count each word in each batch
val pairs = words.map(word => (word, 1))
val wordCounts = pairs.reduceByKey(_ + _)
// Print a few of the counts to the console
wordCounts.print()
ssc.start() // Start the computation
ssc.awaitTermination() // Wait for the computation to terminate
B终端此时会一直打印时间戳。
在终端A,输入任何空格分开的英语单词或文章。
B终端会显示实时的wordcount结果。
完成!