SparkStreaming python 读取kafka数据将结果输出到单个指定本地文件
# -*- coding: UTF-8 -*-
#!/bin/env python3 # filename readFromKafkaStreamingGetLocation.py import IP
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import datetime class KafkaMessageParse: def extractFromKafka(self,kafkainfo):
if type(kafkainfo) is tuple and len(kafkainfo) == 2:
return kafkainfo[1] def lineFromLines(self,lines):
if lines is not None and len(lines) > 0:
return lines.strip().split("\n") def messageFromLine(self,line):
if line is not None and "message" in line.keys():
return line.get("message") def ip2location(self,ip):
result = []
country = 'country'
province = 'province'
city = 'city'
ipinfo = IP.find(ip.strip())
try:
location = ipinfo.split("\t")
if len(location) == 3:
country = location[0]
province = location[1]
city = location[2]
elif len(location) == 2:
country = location[0]
province = location[1]
else:
pass
except Exception:
pass
result.append(ip)
result.append(country)
result.append(province)
result.append(city)
return result def vlistfromkv(self, strori, sep1, sep2):
resultlist = []
fields = strori.split(sep1)
for field in fields:
kv = field.split(sep2)
resultlist.append(kv[1])
return resultlist def extractFromMessage(self, message):
if message is not None and len(message) > 1:
if len(message.split("\u0001")) == 8:
resultlist = self.vlistfromkv(message, "\x01", "\x02")
source = resultlist.pop()
ip = resultlist.pop()
resultlist.extend(self.ip2location(ip))
resultlist.append(source)
result = "\x01".join(resultlist)
return result def tpprint(val, num=10000):
"""
Print the first num elements of each RDD generated in this DStream.
@param num: the number of elements from the first will be printed.
"""
def takeAndPrint(time, rdd):
taken = rdd.take(num + 1)
print("########################")
print("Time: %s" % time)
print("########################")
DATEFORMAT = '%Y%m%d'
today = datetime.datetime.now().strftime(DATEFORMAT)
myfile = open("/data/speech/speech." + today, "a")
for record in taken[:num]:
print(record)
myfile.write(str(record)+"\n")
myfile.close()
if len(taken) > num:
print("...")
print("") val.foreachRDD(takeAndPrint) if __name__ == '__main__':
zkQuorum = 'datacollect-1:2181,datacollect-2:2181,datacollect-3:2181'
topic = {'speech-1': 1, 'speech-2': 1, 'speech-3': 1, 'speech-4':1, 'speech-5':1}
groupid = "rokid-speech-get-location"
master = "local[*]"
appName = "SparkStreamingRokid"
timecell = 5 sc = SparkContext(master=master, appName=appName)
ssc = StreamingContext(sc, timecell)
# ssc.checkpoint("checkpoint_"+time.strftime("%Y-%m-%d", time.localtime(time.time()))) kvs = KafkaUtils.createStream(ssc, zkQuorum, groupid, topic)
kmp = KafkaMessageParse()
lines = kvs.map(lambda x: kmp.extractFromKafka(x))
lines1 = lines.flatMap(lambda x: kmp.lineFromLines(x))
valuedict = lines1.map(lambda x: eval(x))
message = valuedict.map(lambda x: kmp.messageFromLine(x))
rdd2 = message.map(lambda x: kmp.extractFromMessage(x)) # rdd2.pprint() tpprint(rdd2)
# rdd2.fileprint(filepath="result.txt") # rdd2.foreachRDD().saveAsTextFiles("/home/admin/agent/spark/result.txt") # sc.parallelize(rdd2.cache()).saveAsTextFile("/home/admin/agent/spark/result", "txt") # rdd2.repartition(1).saveAsTextFiles("/home/admin/agent/spark/result.txt") ssc.start()
ssc.awaitTermination()
主要是重写pprint()函数
参考:https://stackoverflow.com/questions/37864526/append-spark-dstream-to-a-single-file-in-python
SparkStreaming python 读取kafka数据将结果输出到单个指定本地文件的更多相关文章
- 使用spark-streaming实时读取Kafka数据统计结果存入MySQL
在这篇文章里,我们模拟了一个场景,实时分析订单数据,统计实时收益. 场景模拟 我试图覆盖工程上最为常用的一个场景: 1)首先,向Kafka里实时的写入订单数据,JSON格式,包含订单ID-订单类型-订 ...
- SparkStreaming直连方式读取kafka数据,使用MySQL保存偏移量
SparkStreaming直连方式读取kafka数据,使用MySQL保存偏移量 1. ScalikeJDBC 2.配置文件 3.导入依赖的jar包 4.源码测试 通过MySQL保存kafka的偏移量 ...
- Windows下Python读取GRIB数据
之前写了一篇<基于Python的GRIB数据可视化>的文章,好多博友在评论里问我Windows系统下如何读取GRIB数据,在这里我做一下说明. 一.在Windows下Python为什么无法 ...
- Python读取JSON数据,并解决字符集不匹配问题
今天来谈一谈Python解析JSON数据,并写入到本地文件的一个小例子. – 思路如下 从一个返回JSON天气数据的网站获取到目标JSON数据串 使用Python解析出需要的部分 写入到本地文件,供其 ...
- python 读取excel数据并将测试结果填入Excel
python 读取excel数据并将测试结果填入Excel 读取一个Excel中的一条数据用例,请求接口,然后返回结果并反填到excel中.过程中会生成请求回来的文本,当然还会生成一个xml文件.具体 ...
- flume 读取kafka 数据
本文介绍flume读取kafka数据的方法 代码: /************************************************************************* ...
- spark读取kafka数据 createStream和createDirectStream的区别
1.KafkaUtils.createDstream 构造函数为KafkaUtils.createDstream(ssc, [zk], [consumer group id], [per-topic, ...
- Python读取excel 数据
1.安装xlrd 2.官网 通过官网来查看如何使用python读取Excel,python excel官网: http://www.python-excel.org/ 实例: (1)Excel内容 把 ...
- Python读取Excel数据并根据列名取值
一直想将自己接触到的东西梳理一遍,可就是迈不出第一步,希望从这篇总结开始不要再做行动的矮人了. 最近测试过程中需要用到python读取excel用例数据,于是去了解和学习了下xlrd库,这里只记录使用 ...
随机推荐
- Linux修改终端提示符
打开~/.bashrc可以看到命令提示的内容为:\u@\h\w\$ \u表示用户名,\h表示主机名,\w表示当前目录,\$表示命令提示符(普通用户$,超级用户#) 这个命令提示符有点长,很碍事,\u@ ...
- Fedora 20 安装搜狗拼音输入法
1.卸载ibus sudo yum remove ibus gsettings set org.gnome.settings-daemon.plugins.keyboard active fal ...
- linux达人养成计划学习笔记(六)—— 挂载命令
一.查询与自动挂载 mount #查询系统中已挂载的设备 mount -a #根据配置文件/etc/fstab的内容,自动挂载 二.挂载命令格式 mount [-t 文件系统] [-o 特殊选项] 设 ...
- HDU 4602 Partition (矩阵乘法)
Partition Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total S ...
- IIS的应用程序池优化方法
IIS应用程序池优化方案 服务器经常产生“应用程序池 'DefaultAppPool' 提供服务的进程关闭时间超过了限制.进程 ID 是 '3504'.”的错误,导致iis处于假死状态,经了解是IIS ...
- 【C#】C#创建Windows Service服务
目录结构: contents structure [+] 创建Windows服务 配置 安装Windows服务 在Visual Studio中调试 常见问题 最近写了一个TCP连接的程序,由于这种通信 ...
- bootstrap-table 的 toolbar 能去掉显示吗?
我想禁用所有的toolbar,因为我显示的要求很简单,所以不想要所有的toolbar,这样可以省掉一行,但找不到方法.谢谢! data-show-columns="false"就行 ...
- 转 linux进程内存到底怎么看 剖析top命令显示的VIRT RES SHR值
引 言: top命令作为Linux下最常用的性能分析工具之一,可以监控.收集进程的CPU.IO.内存使用情况.比如我们可以通过top命令获得一个进程使用了多少虚拟内存(VIRT).物理内存(RES). ...
- 忙里偷闲写的小例子---读取android根目录下的文件或文件夹
最近几天真的是各种意义上的忙,忙着考试,还要忙着课程设计,手上又有外包的项目,另一边学校的项目还要搞,自己的东西还在文档阶段,真的是让人想死啊!! 近半个月来,C#这方面的编码比较多,android和 ...
- [转]Jackson 解析json数据之忽略解析字段注解@JsonIgnoreProperties
以前解析json用的惯的就是Google的gson了,用惯了基本就用它了,一直也没发现什么大问题,因为都是解析简单的json数据.但是最近学习springboot,要解析一个比较复杂的json数据.就 ...