spark 消费kafka的数据

通过flume将日志数据读取到kafka中,然后再利用spark去消费kafka的数据,

1.保证zookeeper服务一直开启

2.配置flume文件,其配置信息如下

a1.sources = r1
a1.sinks = k1
a1.channels = c1

# Describe/configure the source
a1.sources.r1.type = exec
a1.sources.r1.command = tail -F /opt/data/wfbmall/16/wfbmall.log

# Describe the sink
#a1.sinks.k1.type = logger
a1.sinks.k1.type = org.apache.flume.sink.kafka.KafkaSink
a1.sinks.k1.topic = test
a1.sinks.k1.brokerList = master:9092
a1.sinks.k1.requiredAcks = 1
a1.sinks.k1.batchSize = 20

# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 10000
a1.channels.c1.byteCapacityBufferPercentage = 20
a1.channels.c1.byteCapacity = 800000
a1.channels.c1.transactionCapacity = 100
a1.channels.c1.keep-alive = 60   
# Bind the source and sink to the channel
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1

可以通过 来查看kafka里的数据

[root@master ~]# /opt/soft/kafka_2.11-0.11/bin/kafka-console-consumer.sh --bootstrap-server master:9092 --from-beginning --topic test

4.最后可以配置saprk 进行实时统计数据

# coding=UTF-8
from __future__ import print_function 
import sys 
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils


sc = SparkContext(appName="streamingkafka")
sc.setLogLevel("WARN") # 减少shell打印日志
ssc = StreamingContext(sc, 5) # 5秒的计算窗口
brokers='master:9092'
topic = 'test'
kafka_streaming_rdd = KafkaUtils.createDirectStream(ssc, [topic], {"metadata.broker.list": brokers})
lines_rdd = kafka_streaming_rdd.map(lambda x: x[1]).filter(lambda x: "login, start" in x).map(lambda x: ("login_start", 1)).reduceByKey(lambda a, b : a + b)

lines_rdd.pprint()
ssc.start()
ssc.awaitTermination()

5.进行调用文件

[root@master spark-2.4.5]# bin/spark-submit --jars jars/spark-streaming-kafka-0-8_2.11-2.3.3.jar bin/kafka-spark_20210401.py

其显示结果为

spark 消费kafka的数据

 

上一篇:D. Dr. Evil Underscores(思维+贪心+字典树dfs)


下一篇:【数值分析】发电机方程的数值求解及MATLAB仿真