网上有很多pyspark streaming的测试代码,不过大多都是需要结合kafka做消息来源
由于懒得搭kafka,所以想本地生成随机数据作为streaming源,测试spark streaming
google查了一些文章,其实spark github中就有类似代码,只不过文件名叫 hdfs_wordcount.py,是针对hdfs的example
https://github.com/apache/spark/blob/master/examples/src/main/python/streaming/hdfs_wordcount.py
参考这个代码来自己测试
环境:
hostip:192.168.1.20
spark standalone
代码:
"""
Filename: test_spark_streaming.py
Author: Si Yu
Date: 01/03/2019
"""
from __future__ import print_function
import sys
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
if __name__ == "__main__":
LOCALDIR = "/tmp/testfiles"
sc = SparkContext(master="spark://192.168.1.20:7077", appName="PythonStreamingLocalFilesWordCount")
ssc = StreamingContext(sc, 10)
lines = ssc.textFileStream(LOCALDIR)
words = lines.flatMap(lambda line: line.split(" "))
pairs = words.map(lambda word: (word, 1))
wordCounts = pairs.reduceByKey(lambda x, y: x+y)
wordCounts.pprint()
ssc.start()
ssc.awaitTermination()
注意:
启动程序后,文件夹中的新文件才会被streaming捕获到,开始试了半天没反应,最后才发现