# -*- 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. LUA可变长参数 ... 三个点

    本文翻译自 LUA官方文档 When a function is called, the list of arguments is adjusted to the length of the list ...

  2. at com.mysql.jdbc.SQLError.createSQLException

    WARN run, com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@1de6191 -- APPARENT DEA ...

  3. iOS 10 的一个重要更新-新的通知推送 API

    iOS 10 最重要的变化可能就是通知 API 的重构了.本文用一个简单闹钟的例子介绍了 User Notification 的 API 变化和新功能. 简介 很久以前,开发者就可以在 iOS 里预约 ...

  4. 如何搜索IP的地理位置

    如何搜索IP的地理位置 http://www.ip138.com/ 打开上边这个网页以后,会显示自身的IP及地理位置,,,,也可以搜索别人的IP和地理位置,手机号等:截图如下:

  5. 【Android】详解Android动画

    目录结构: contents structure [+] 补间动画 使用java代码实现Alpha.Rotate.Scale.Translate动画 通过xml文件实现Alpha.Rotate.Sca ...

  6. 【Spring】Spring之依赖注入(DI)传递参数的方式

    DI依赖注入传入参数的方式,这里介绍了基本数据类型,集合,符合数据类型的传递(String类型比较特殊,其传递值和基本数据类型的方法一致) 注入基本数据类型和String类型 通过setter方法注入 ...

  7. [转]SpringMVC中使用Interceptor拦截器

    SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那 ...

  8. iphone 4s插件的安装,问题及美化

    此处iphone4s为美版,系统版本为5.0.1 首先添加我自己的weiphone源:http://apt.weiphone.com/u/2903862以及破解资源源:http://cydia.xse ...

  9. 7 款顶级的开源 Web 分析软件

    Web 分析无非就是 Web 流量的测量.但它并不限于测量网络流量,还包括: 分析 数据采集 为了了解和优化网页而上报网络数据 Google Analytics是最广泛使用的基于云的网络分析服务.不过 ...

  10. C# string和byte[]的转换

    转自 http://www.cnblogs.com/Mainz/archive/2008/04/09/String_Byte_Array_Convert_CSharp.html string类型转成b ...