2.6 spark实战案例:实时日志分析

  • 2.6.1 交互流程图

  • 2.6.2 客户端监听器(java)
@SuppressWarnings("static-access")
private void handleSocket() {
lock.lock();
Writer writer = null;
RandomAccessFile raf = null; try {
File file = new File(filepath);
raf = new RandomAccessFile(file, "r");
raf.seek(pointer);
writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8"); String line = null; while ((line = raf.readLine()) != null) {
if (Strings.isBlank(line)) {
continue;
} line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
writer.write(line.concat("\n"));
writer.flush();
logger.info("线程:{}----起始位置:{}----读取文件\n{} :",Thread.currentThread().getName(), pointer, line); pointer = raf.getFilePointer();
}
Thread.currentThread().sleep(2000);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
} finally {
lock.unlock();
fclose(writer, raf);
} }
  • 2.6.3 sparkStream实时数据接收(python)
conf = SparkConf()
conf.setAppName("HIS实时日志分析")
conf.setMaster('yarn') # spark standalone
conf.set('spark.executor.instances', 8) # cluster on yarn
conf.set('spark.executor.memory', '1g')
conf.set('spark.executor.cores', '1')
# conf.set('spark.cores.max', '2')
# conf.set('spark.logConf', True)
conf.set('spark.streaming.blockInterval', 1000*4) # restart receiver interval sc = SparkContext(conf = conf)
sc.setLogLevel('ERROR')
sc.setCheckpointDir('hdfs://hadoop01:9000/hadoop/upload/checkpoint/') ssc = StreamingContext(sc, 30) # time interval at which splits streaming data into block lines = ssc.socketTextStream(str(ip), int(port))
# lines.pprint()
lines.foreachRDD(requestLog)
lines.foreachRDD(errorLog)
ssc.start()
ssc.awaitTermination()
  • 2.6.4 sparklSQL、RDD结算、结构化搜索、结构存储mongoDB(python)
 def getSparkSessionInstance(sparkConf):
'''
:@desc 多个RDD全局共享sparksession
.config("spark.mongodb.input.uri", "mongodb://127.0.0.1/test.coll") \
.config("spark.mongodb.output.uri", "mongodb://adxkj:123456@192.168.0.252:27017/") \
:param sparkConf:
:return:
'''
if ('sparkSessionSingletonInstance' not in globals()):
globals()['sparkSessionSingletonInstance'] = SparkSession \
.builder \
.config(conf=sparkConf) \
.getOrCreate()
return globals()['sparkSessionSingletonInstance'] def timeFomate(x):
'''
:@desc 处理时间
:param x:
:return:
'''
if not isinstance(x, list):
return None # filter microsenconds
x.insert(0, ' '.join(x[0:2]))
x.pop(1)
x.pop(1) # filter '[]'
rx = re.compile('([\[\]\',])')
# text = rx.sub(r'\\\1', text)
x = [rx.sub(r'', x[i]) for i in range(len(x))] # string to time
x[0] = x[0][: x[0].find('.')]
x[0] = ''.join(x[0])
x[0] = datetime.strptime(x[0], '%Y-%m-%d %H:%M:%S') return x def sqlMysql(sqlResult, table, url="jdbc:mysql://192.168.0.252:3306/hisLog", user='root', password=""):
'''
:@desc sql结果保存
:param sqlResult:
:param table:
:param url:
:param user:
:param password:
:return:
'''
try:
sqlResult.write \
.mode('append') \
.format("jdbc") \
.option("url", url) \
.option("dbtable", table) \
.option("user", user) \
.option("password", password) \
.save()
except:
excType, excValue, excTraceback = sys.exc_info()
traceback.print_exception(excType, excValue, excTraceback, limit=3)
# print(excValue)
# traceback.print_tb(excTraceback) def sqlMongodb(sqlResult, table):
'''
:@desc sql结果保存
:param sqlResult:
:param table:
:param url:
:param user:
:param password:
:return:
'''
try:
sqlResult.\
write.\
format("com.mongodb.spark.sql.DefaultSource"). \
options(uri="mongodb://adxkj:123456@192.168.0.252:27017/hislog",
database="hislog", collection=table, user="adxkj", password="123456").\
mode("append").\
save()
except:
excType, excValue, excTraceback = sys.exc_info()
traceback.print_exception(excType, excValue, excTraceback, limit=3)
# print(excValue)
# traceback.print_tb(excTraceback) def decodeStr(x) :
'''
:@desc base64解码
:param x:
:return:
''' try:
if x[9].strip() != '' :
x[9] = base64.b64decode(x[9].encode("utf-8")).decode("utf-8")
# x[9] = x[9][:5000] #mysql if x[11].strip() != '':
x[11] = base64.b64decode(x[11].encode("utf-8")).decode("utf-8")
# x[11] = x[11][:5000] #mysql if len(x) > 12 and x[12].strip() != '':
x[12] = base64.b64decode(x[12].encode("utf-8")).decode("utf-8") except Exception as e:
print("不能解码:", x, e) return x def analyMod(x) :
'''
:@desc 通过uri匹配模块
:param x:
:return:
'''
if x[6].strip() == ' ':
return None hasMatch = False for k, v in URI_MODULES.items() :
if x[6].strip().startswith('/' + k) :
hasMatch = True
x.append(v) if not hasMatch:
x.append('公共模块') return x def requestLog(time, rdd):
'''
:@desc 请求日志分析
:param time:
:param rdd:
:return:
''' logging.info("+++++handle request log:length:%d,获取内容:++++++++++" % (rdd.count())) if rdd.isEmpty():
return None logging.info("++++++++++++++++++++++处理requestLog+++++++++++++++++++++++++++++++") reqrdd = rdd.map(lambda x: x.split(' ')).\
filter(lambda x: len(x) > 12 and x[4].find('http-nio-') > 0 and x[2].strip() == 'INFO').\
filter(lambda x: x[8].strip().upper().startswith('POST') or x[8].strip().upper().startswith('GET')).\
map(timeFomate).\
map(decodeStr).\
map(analyMod) reqrdd.cache()
reqrdd.checkpoint() # checkpoint先cache避免计算两次,以前的rdd销毁 sqlRdd = reqrdd.map(lambda x: Row(time=x[0], level=x[1], clz=x[2], thread=x[3], user=x[4], depart=x[5],
uri=x[6], method=x[7], ip=x[8], request=x[9], oplen=x[10],
respone=x[11], mod=x[12])) # rdd持久化,降低内存消耗, cache onliy for StorageLevel.MEMORY_ONLY
# reqrdd.persist(storageLevel=StorageLevel.MEMORY_AND_DISK_SER) if reqrdd.isEmpty():
return None spark = getSparkSessionInstance(rdd.context.getConf())
df = spark.createDataFrame(sqlRdd)
df.createOrReplaceTempView(REQUEST_TABLE) # 结构化后再分析
sqlresult = spark.sql("SELECT * FROM " + REQUEST_TABLE)
sqlresult.show() # 保存
sqlMongodb(sqlresult, REQUEST_TABLE) def errorLog(time, rdd):
'''
:@desc 错误日志分析
:param time:
:param rdd:
:return:
''' logging.info("+++++handle error log:length:%d,获取内容:++++++++++" % (rdd.count())) if rdd.isEmpty():
return None logging.info("++++++++++++++++++++++处理errorLog+++++++++++++++++++++++++++++++") errorrdd = rdd.map(lambda x: x.split(' ')). \
filter(lambda x: len(x) > 13 and x[2].strip().upper().startswith('ERROR')). \
map(timeFomate). \
map(decodeStr). \
map(analyMod). \
map(lambda x: Row(time=x[0], level=x[1], clz=x[2], thread=x[3], user=x[4], depart=x[5],
uri=x[6], method=x[7], ip=x[8], request=x[9], oplen=x[10],
respone=x[11], stack=x[12], mod=x[13]))
# rdd持久化,降低内存消耗
errorrdd.persist(storageLevel=StorageLevel.MEMORY_AND_DISK_SER) if errorrdd.isEmpty():
return None spark = getSparkSessionInstance(rdd.context.getConf())
df = spark.createDataFrame(errorrdd)
df.createOrReplaceTempView(ERROR_TABLE) # 结构化后再分析
sqlresult = spark.sql("SELECT * FROM " + ERROR_TABLE)
sqlresult.show() # 保存
sqlMongodb(sqlresult, ERROR_TABLE)

备注:需要完整代码请联系作者@狼

大数据实战手册-开发篇之spark实战案例:实时日志分析的更多相关文章

  1. 苏宁基于Spark Streaming的实时日志分析系统实践 Spark Streaming 在数据平台日志解析功能的应用

    https://mp.weixin.qq.com/s/KPTM02-ICt72_7ZdRZIHBA 苏宁基于Spark Streaming的实时日志分析系统实践 原创: AI+落地实践 AI前线 20 ...

  2. Spark 实践——基于 Spark Streaming 的实时日志分析系统

    本文基于<Spark 最佳实践>第6章 Spark 流式计算. 我们知道网站用户访问流量是不间断的,基于网站的访问日志,即 Web log 分析是典型的流式实时计算应用场景.比如百度统计, ...

  3. Java,面试题,简历,Linux,大数据,常用开发工具类,API文档,电子书,各种思维导图资源,百度网盘资源,BBS论坛系统 ERP管理系统 OA办公自动化管理系统 车辆管理系统 各种后台管理系统

    Java,面试题,简历,Linux,大数据,常用开发工具类,API文档,电子书,各种思维导图资源,百度网盘资源BBS论坛系统 ERP管理系统 OA办公自动化管理系统 车辆管理系统 家庭理财系统 各种后 ...

  4. GIS+=地理信息+行业+大数据——基于云环境流处理平台下的实时交通创新型app

    应用程序已经是近代的一个最重要的IT创新.应用程序是连接用户和数据之间的桥梁,提供即时訪问信息是最方便且呈现的方式也是easy理解的和令人惬意的. 然而,app开发人员.尤其是后端平台能力,一直在努力 ...

  5. Spark SQL慕课网日志分析(1)--系列软件(单机)安装配置使用

    来源: 慕课网 Spark SQL慕课网日志分析_大数据实战 目标: spark系列软件的伪分布式的安装.配置.编译 spark的使用 系统: mac 10.13.3 /ubuntu 16.06,两个 ...

  6. 大数据项目实践:基于hadoop+spark+mongodb+mysql+c#开发医院临床知识库系统

    一.前言 从20世纪90年代数字化医院概念提出到至今的20多年时间,数字化医院(Digital Hospital)在国内各大医院飞速的普及推广发展,并取得骄人成绩.不但有数字化医院管理信息系统(HIS ...

  7. 大数据核心知识点:Hbase、Spark、Hive、MapReduce概念理解,特点及机制

    今天,上海尚学堂大数据培训班毕业的一位学生去参加易普软件公司面试,应聘的职位是大数据开发.面试官问了他10个问题,主要集中在Hbase.Spark.Hive和MapReduce上,基础概念.特点.应用 ...

  8. 大数据的前世今生【Hadoop、Spark】

      一.大数据简介 大数据是一个很热门的话题,但它是什么时候开始兴起的呢? 大数据[big data]这个词最早在UNIX用户协会的会议上被使用,来自SGI公司的科学家在其文章“大数据与下一代基础架构 ...

  9. 了解大数据的技术生态系统 Hadoop,hive,spark(转载)

    首先给出原文链接: 原文链接 大数据本身是一个很宽泛的概念,Hadoop生态圈(或者泛生态圈)基本上都是为了处理超过单机尺度的数据处理而诞生的.你能够把它比作一个厨房所以须要的各种工具. 锅碗瓢盆,各 ...

  10. 一文教你看懂大数据的技术生态圈:Hadoop,hive,spark

    转自:https://www.cnblogs.com/reed/p/7730360.html 大数据本身是个很宽泛的概念,Hadoop生态圈(或者泛生态圈)基本上都是为了处理超过单机尺度的数据处理而诞 ...

随机推荐

  1. Django笔记十五之in查询及date日期相关过滤操作

    这一篇介绍关于范围,日期的筛选 in range date year week weekday quarter hour 1.in in 对应于 MySQL 中的 in 操作,可以接受数组.元组等类型 ...

  2. 在k8s(kubernetes) 上安装 ingress V1.1.0

    Ingress 公开了从集群外部到集群内服务的 HTTP 和 HTTPS 路由.流量路由由 Ingress 资源上定义的规则控制. 下面是一个将所有流量都发送到同一 Service 的简单 Ingre ...

  3. [数据库]mysql/mysqldump命令帮助说明

    1 mysql [root@test ~]# mysql --help mysql Ver 14.14 Distrib 5.7.24-27, for Linux (x86_64) using 6.0 ...

  4. String知识点整理

    使用双引号创建字符串时,JVM会现在字符串常量池中查找是否已存在该字符串,存在则返回,不存在则在池中创建后再返回.与此同时,使用String的intern方法也是类似处理. 使用new String的 ...

  5. Linux下ftp常见问题总结

    Linux下ftp常见问题总结 似乎拖欠了几篇文章了@_@,来公司半年了,成长了不少!从大学毕业,直到看到http://blog.csdn.net/leixiaohua1020  雷霄骅(然而天妒英才 ...

  6. 性能_2 Jmeter脚本增强

    一.写脚本注意事项(回顾): 协议: http,https必须写 域名或ip: 不能有/ 请求方法: 看清楚接口文档 路径: 不要把 域名和ip再次 路径中,前后空格要看清楚 %20 空格的urlen ...

  7. Mastering Regular Expressions(精通正则表达式) 阅读笔记:第一章,概念

    Real Scenario(现实场景) Here's the scenario: you're given the job of checking the pages on a web server ...

  8. 一文快速入门体验 Hibernate

    前言 Hibernate 是一个优秀的持久层的框架,当然,虽然现在说用得比较多的是 MyBaits,但是我工作中也不得不接触 Hibernate,特别是一些老项目需要你维护的时候.所以,在此写下这篇文 ...

  9. 2022-06-10:薯队长从北向南穿过一片红薯地(南北长M,东西宽N),红薯地被划分为1x1的方格, 他可以从北边的任何一个格子出发,到达南边的任何一个格子, 但每一步只能走到东南、正南、西南方向的

    2022-06-10:薯队长从北向南穿过一片红薯地(南北长M,东西宽N),红薯地被划分为1x1的方格, 他可以从北边的任何一个格子出发,到达南边的任何一个格子, 但每一步只能走到东南.正南.西南方向的 ...

  10. GPT大语言模型Alpaca-lora本地化部署实践【大语言模型实践一】

    模型介绍 Alpaca模型是斯坦福大学研发的LLM(Large Language Model,大语言)开源模型,是一个在52K指令上从LLaMA 7B(Meta公司开源的7B)模型微调而来,具有70亿 ...