# -*- 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数据将结果输出到单个指定本地文件的更多相关文章

  1. 使用spark-streaming实时读取Kafka数据统计结果存入MySQL

    在这篇文章里,我们模拟了一个场景,实时分析订单数据,统计实时收益. 场景模拟 我试图覆盖工程上最为常用的一个场景: 1)首先,向Kafka里实时的写入订单数据,JSON格式,包含订单ID-订单类型-订 ...

  2. SparkStreaming直连方式读取kafka数据,使用MySQL保存偏移量

    SparkStreaming直连方式读取kafka数据,使用MySQL保存偏移量 1. ScalikeJDBC 2.配置文件 3.导入依赖的jar包 4.源码测试 通过MySQL保存kafka的偏移量 ...

  3. Windows下Python读取GRIB数据

    之前写了一篇<基于Python的GRIB数据可视化>的文章,好多博友在评论里问我Windows系统下如何读取GRIB数据,在这里我做一下说明. 一.在Windows下Python为什么无法 ...

  4. Python读取JSON数据,并解决字符集不匹配问题

    今天来谈一谈Python解析JSON数据,并写入到本地文件的一个小例子. – 思路如下 从一个返回JSON天气数据的网站获取到目标JSON数据串 使用Python解析出需要的部分 写入到本地文件,供其 ...

  5. python 读取excel数据并将测试结果填入Excel

    python 读取excel数据并将测试结果填入Excel 读取一个Excel中的一条数据用例,请求接口,然后返回结果并反填到excel中.过程中会生成请求回来的文本,当然还会生成一个xml文件.具体 ...

  6. flume 读取kafka 数据

    本文介绍flume读取kafka数据的方法 代码: /************************************************************************* ...

  7. spark读取kafka数据 createStream和createDirectStream的区别

    1.KafkaUtils.createDstream 构造函数为KafkaUtils.createDstream(ssc, [zk], [consumer group id], [per-topic, ...

  8. Python读取excel 数据

    1.安装xlrd 2.官网 通过官网来查看如何使用python读取Excel,python excel官网: http://www.python-excel.org/ 实例: (1)Excel内容 把 ...

  9. Python读取Excel数据并根据列名取值

    一直想将自己接触到的东西梳理一遍,可就是迈不出第一步,希望从这篇总结开始不要再做行动的矮人了. 最近测试过程中需要用到python读取excel用例数据,于是去了解和学习了下xlrd库,这里只记录使用 ...

随机推荐

  1. Eclipse导入项目时出错提示 project is missing required library

    Eclipse导入(import)项目时出错提示 project is missing required library... 以至于不能build... 然后项目会有红色感叹号: [解决办法] 右击 ...

  2. Apache启用GZIP压缩网页传输

    首先我们先了解Apache Gzip的相关资料. 一.gzip介绍 Gzip是一种流行的文件压缩算法,现在的应用十分广泛,尤其是在Linux平台.当应用Gzip压缩到一个纯文本文件时,效果是非常明显的 ...

  3. linux达人养成计划学习笔记(三)—— 帮助命令

    一.帮助命令man 1.基本使用方法: man 命令 #获取指定命令的帮助选项: -f 查看命令拥有的帮助级别 相当于whatis,也可以使用whereis来查询 -num 调用对应等级的帮助文件 - ...

  4. 轻量级验证码生成插件webutil-licenseImage源码与实例应用

    webutil-licenseImage 插件内置4种验证码样式,支持用户扩展.自定义样式实现简单验证码. 源码脱管地址: http://code.google.com/p/licenseimage/ ...

  5. Python - 列表解析式/生成器表达式

    列表解析式: [expr for iter_var in iterable if cond_expr] 生成器表达式: (expr for iter_var in iterable if cond_e ...

  6. 启用跨源请求 (CORS)

    https://docs.microsoft.com/zh-cn/aspnet/core/security/cors

  7. appium简明教程(5)——appium client方法一览

    appium client扩展了原生的webdriver client方法 下面以java代码为例,简单过一下appium client提供的适合移动端使用的新方法 resetApp() getApp ...

  8. Android帧布局<TabHost>标签

    先贴上一段代码: main.xml: <p><?xml version="1.0" encoding="utf-8"?> <Tab ...

  9. 转 阿里Dubbo疯狂更新,关Spring Cloud什么事?

    原文地址: http://www.ityouknow.com/springcloud/2017/11/20/dubbo-update-again.html阿里Dubbo疯狂更新,关Spring Clo ...

  10. VB通用数据库操作方法

    1.VB通用数据操作方法. 2.通用数据库查询方法. 3.通用数据库操作方法. 'ERP查询数据库 Public Function YZQuery(sqls As String, msgstring ...