Pyspark-从Kafka打印消息

时间:2018-11-18 19:50:14

标签: python apache-spark pyspark apache-kafka

我用生产者和消费者建立了一个kafka系统,将json文件的行作为消息流传输。

使用pyspark,我需要分析不同流式传输窗口的数据。为此,我需要查看pyspark流式传输的数据...该怎么办?

要运行我使用的Yannael's Docker容器代码。这是我的python代码:

# Add dependencies and load modules
import os
os.environ['PYSPARK_SUBMIT_ARGS'] = '--conf spark.ui.port=4040 --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.0.0,com.datastax.spark:spark-cassandra-connector_2.11:2.0.0-M3 pyspark-shell'

from kafka import KafkaConsumer
from random import randint
from time import sleep

# Load modules and start SparkContext  
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext, Row
conf = SparkConf() \
    .setAppName("Streaming test") \
    .setMaster("local[2]") \
    .set("spark.cassandra.connection.host", "127.0.0.1")

try:
    sc.stop()
except:
    pass    

sc = SparkContext(conf=conf) 
sqlContext=SQLContext(sc)
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils

# Create streaming task
ssc = StreamingContext(sc, 0.60)
kafkaStream = KafkaUtils.createStream(ssc, "127.0.0.1:2181", "spark-streaming-consumer", {'test': 1})
ssc.start()

1 个答案:

答案 0 :(得分:1)

您可以致电kafkaStream.pprint()或了解更多信息about structured streaming,并可以像这样打印

query = kafkaStream \
    .writeStream \
    .outputMode("complete") \
    .format("console") \
    .start()

query.awaitTermination()

我看到您有个端点,因此假设您正在编写Cassandra,可以使用Kafka Connect而不是为此编写Spark代码