pyspark(四):sparkStreaming

一、基本概念

1.1 两种数据处理方式

批处理:MapReduce、Spark、Flink

流式处理:Storm、Spark、Flink

Spark和Flink都兼具批处理和流式处理,但原理不同。Spark认为批处理是常态,流式处理是一个特例,所以是微批micro batch。而Flink刚好相反,认为流处理是常态,批处理是流处理的一个特例,所以有window时间窗口的概念。


二、实例

2.1 脚本

from pyspark import SparkContext,SparkConf

from pyspark.streaming import StreamingContext


conf = SparkConf().setMaster("local[2]").setAppName("NetworkWordCount")

sc = SparkContext(conf=conf)

#We create a local StreamingContext with two execution threads, and batch interval of 1 second.

    ssc = StreamingContext(sc,3)

lines = ssc.socketTextStream("localhost",9999)

words = lines.flatMap(lambda x:x.split(" "))

pairs = words.map(lambda x:(x,1))

wordCounts = pairs.reduceByKey(lambda x,y:x+y)

wordCounts.pprint()

ssc.start()

ssc.awaitTermination()

2.2 cmd中输入

nc -lk 9999

然后输入一些字符,以空格隔开,换行表示输入完成

2.3 运行结果

-------------------------------------------

Time: 2020-06-28 19:47:15

-------------------------------------------

('b', 3)

('c', 2)

('a', 4)

('e', 2)

('d', 1)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。