spark stream初探

spark带了一个NetworkWordCount测试程序,用以统计来自某TCP连接的单词输入:

/usr/local/spark/bin/run-example streaming.NetworkWordCount localhost 9999

再启动netcat:
nc -lk 9999

尝试输入一些单词:

hello world
damn it

可以看到NetworkWordCount产生如下输出:

-------------------------------------------
Time: 1425866862000 ms
-------------------------------------------
(world,1)
(hello,1)
-------------------------------------------
Time: 1425866877000 ms
-------------------------------------------
(damn,1)
(it,1)

也可以手动在shell里输入NetworkWordCount的代码:

scala> :paste
// Entering paste mode (ctrl-D to finish)

import org.apache.spark._
import org.apache.spark.streaming._
import org.apache.spark.streaming.StreamingContext._

// Create a local StreamingContext with two working thread and batch interval of 1 second.
// The master requires 2 cores to prevent from a starvation scenario.

val conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount")
val ssc = new StreamingContext(conf, Seconds(1))
// Create a DStream that will connect to hostname:port, like localhost:9999
val lines = ssc.socketTextStream("localhost", 9999)
// Split each line into words
val words = lines.flatMap(_.split(" "))
val pairs = words.map(word => (word, 1))
val wordCounts = pairs.reduceByKey(_ + _)

// Print the first ten elements of each RDD generated in this DStream to the console
wordCounts.print()
ssc.start()             // Start the computation
ssc.awaitTermination()  // Wait for the computation to terminate

执行后,即可在屏幕上得到类似的输出。

转载于:https://www.cnblogs.com/bluejoe/p/5115854.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值