日志=>flume=>kafka=>spark streaming=>hbase
日志=>flume=>kafka=>spark streaming=>hbase
日志部分
#coding=UTF-8
import random
import time url_paths = [
"class/112.html",
"class/128.html",
"learn/821",
"class/145.html",
"class/146.html",
"class/131.html",
"class/130.html",
"course/list"
] ip_slices = [132,156,124,10, 29, 167,143,187,30, 46, 55, 63, 72, 87,98,168] http_referers = [
"http://www.baidu.com/s?wd={query}",
"http://www.sogou.com/web?query={query}",
"https://search.yahoo.com/search?p={query}",
"http://www.bing.com/search?q={query}"
] search_keyword = ["Spark SQL实战", "Hadoop基础", "Storm实战", "Spark Streaming实战", "大数据面试"] status_codes = ["", "", ""] def sample_url():
return random.sample(url_paths,1)[0] def sample_ip():
slice = random.sample(ip_slices,4)
return ".".join([str(item) for item in slice]) def sample_status_code():
return random.sample(status_codes,1)[0] def sample_referer():
if random.uniform(0, 1) > 0.2:
return "-" refer_str = random.sample(http_referers, 1)
query_str = random.sample(search_keyword, 1)
return refer_str[0].format(query=query_str[0]) def generate_log(count=3):
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
f = open("/home/hadoop/data/project/logs/access.log", "w+")
while count >= 1:
query_log = "{ip}\t[{local_time}]\t\"GET /{url} HTTP/1.1\"\t{status_code}\t\"{referer}\"".format(ip=sample_ip() , local_time=time_str, url=sample_url(), status_code=sample_status_code(), referer=sample_referer())
print query_log
f.write(query_log + "\n")
count = count - 1 if __name__ == '__main__':
#print sample_ip()
#print sample_url()
generate_log(10)
flume对接日志部分
exec-memory-kafka.conf
#exec-memory-kafka exec-memory-kafka.sources = exec-source
exec-memory-kafka.channels = memory-channel
exec-memory-kafka.sinks = kafka-sink exec-memory-kafka.sources.exec-source.type = exec
exec-memory-kafka.sources.exec-source.command = tail -F /home/hadoop/data/project/logs/access.log
exec-memory-kafka.sources.exec-source.shell = /bin/sh -c
exec-memory-kafka.sources.exec-source.channels = memory-channel exec-memory-kafka.channels.memory-channel.type = memory exec-memory-kafka.sinks.kafka-sink.type = org.apache.flume.sink.kafka.KafkaSink
exec-memory-kafka.sinks.kafka-sink.topic = streamingtopic
exec-memory-kafka.sinks.kafka-sink.brokerList = hadoop:9092
exec-memory-kafka.sinks.kafka-sink.batchSize = 5
exec-memory-kafka.sinks.kafka-sink.requiredAcks = 1
exec-memory-kafka.sinks.kafka-sink.channel = memory-channel
flume-ng agent \
--name exec-memory-kafka \
--conf $FLUME_HOME/conf \
--conf-file /home/hadoop/data/project/exec-memory-kafka.conf \
-Dflume.root.logger=INFO,console
启动kafka测试消费:kafka-console-consumer.sh --zookeeper hadoop:2181 --topic streamingtopic --from-beginning
启动Hadoop:start-dfs.sh
启动hbase: start-hbase.sh
进入hbase shell:hbase shell -> 查看: list
hbase表设计:
create 'lin_course_clickcount' ,'info'
create 'lin_course_search_clickcount','info'
查看表:scan 'lin_course_clickcount'
rowkey设计:
day_courseid
day_search_courseid
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.lin.spark</groupId>
<artifactId>SparkStreaming</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<scala.version>2.11.8</scala.version>
<kafka.version>0.9.0.0</kafka.version>
<spark.version>2.2.0</spark.version>
<hadoop.version>2.6.0-cdh5.7.0</hadoop.version>
<hbase.version>1.2.0-cdh5.7.0</hbase.version>
</properties> <!--添加cloudera的repository-->
<repositories>
<repository>
<id>cloudera</id>
<url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
</repository>
</repositories> <dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency> <!-- Kafka 依赖-->
<!--
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.11</artifactId>
<version>${kafka.version}</version>
</dependency>
--> <!-- Hadoop 依赖-->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${hadoop.version}</version>
</dependency> <!-- HBase 依赖-->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>${hbase.version}</version>
</dependency> <dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-server</artifactId>
<version>${hbase.version}</version>
</dependency> <!-- Spark Streaming 依赖-->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>${spark.version}</version>
</dependency> <!-- Spark Streaming整合Flume 依赖-->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-flume_2.11</artifactId>
<version>${spark.version}</version>
</dependency> <dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-flume-sink_2.11</artifactId>
<version>${spark.version}</version>
</dependency> <dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
<version>${spark.version}</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency> <!-- Spark SQL 依赖-->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>${spark.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>2.6.5</version>
</dependency> <dependency>
<groupId>net.jpountz.lz4</groupId>
<artifactId>lz4</artifactId>
<version>1.3.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency> <dependency>
<groupId>org.apache.flume.flume-ng-clients</groupId>
<artifactId>flume-ng-log4jappender</artifactId>
<version>1.6.0</version>
</dependency> </dependencies> <build>
<!--
<sourceDirectory>src/main/scala</sourceDirectory>
<testSourceDirectory>src/test/scala</testSourceDirectory>
-->
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<scalaVersion>${scala.version}</scalaVersion>
<args>
<arg>-target:jvm-1.5</arg>
</args>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<buildcommands>
<buildcommand>ch.epfl.lamp.sdt.core.scalabuilder</buildcommand>
</buildcommands>
<additionalProjectnatures>
<projectnature>ch.epfl.lamp.sdt.core.scalanature</projectnature>
</additionalProjectnatures>
<classpathContainers>
<classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
<classpathContainer>ch.epfl.lamp.sdt.launching.SCALA_CONTAINER</classpathContainer>
</classpathContainers>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<configuration>
<scalaVersion>${scala.version}</scalaVersion>
</configuration>
</plugin>
</plugins>
</reporting> </project>
package com.lin.spark.streaming.project.spark import com.lin.spark.streaming.project.dao.{CourseClickCountDAO, CourseSearchClickCountDAO}
import com.lin.spark.streaming.project.domain.{ClickLog, CourseClickCount, CourseSearchClickCount}
import com.lin.spark.streaming.project.utils.DateUtils
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.streaming.{Seconds, StreamingContext} import scala.collection.mutable.ListBuffer /**
* Created by Administrator on 2019/6/6.
*/
object StatStreamingApp {
def main(args: Array[String]): Unit = { if (args.length != 4) {
System.err.println("参数有误!")
System.exit(1)
}
//hadoop:2181 test streamingtopic 2
val Array(zkQuorum, group, topics, numThreads) = args
val conf = new SparkConf().setAppName("KafkaUtil").setMaster("local[4]")
val ssc = new StreamingContext(conf, Seconds(60)) val topicMap = topics.split(",").map((_, numThreads.toInt)).toMap val clickLog = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap).map(_._2) val cleanData = clickLog.map(line => {
val infos = line.split("\t")
//29.98.156.124 2019-06-06 05:37:01 "GET /class/131.html HTTP/1.1" 500 http://www.baidu.com/s?wd=Storm实战
//case class ClickLog(ip:String, time:String, courseId:Int, statusCode:Int, referer:String)
var courseId = 0
val url = infos(2).split(" ")(1)
if (url.startsWith("/class")) {
val urlHTML = url.split("/")(2)
courseId = urlHTML.substring(0, urlHTML.lastIndexOf(".")).toInt
}
ClickLog(infos(0), DateUtils.parseToMinute(infos(1)), courseId, infos(3).toInt, infos(4))
}).filter(clickLog => clickLog.courseId != 0) //存储点击日志
cleanData.map(log => {
(log.time.substring(0, 8) + "_" + log.courseId, 1)
}).reduceByKey(_ + _).foreachRDD(rdd => {
rdd.foreachPartition(partitionReconrds => {
val list = new ListBuffer[CourseClickCount]
partitionReconrds.foreach(pair => {
list.append(CourseClickCount(pair._1, pair._2))
})
CourseClickCountDAO.save(list)
})
}) //存储查询点击日志
cleanData.map(log => { val referer = log.referer.replaceAll("//", "/")
val splits = referer.split("/")
var host = ""
if (splits.length > 2) {
host = splits(1)
}
(host, log.courseId, log.time)
}).filter(x => {
x._1 != ""
}).map(searchLog=>{
(searchLog._3.substring(0,8) + "_" + searchLog._1 + "_" + searchLog._2 , 1)
}).reduceByKey(_ + _).foreachRDD(rdd => {
rdd.foreachPartition(partitionReconrds => {
val list = new ListBuffer[CourseSearchClickCount]
partitionReconrds.foreach(pair => {
list.append(CourseSearchClickCount(pair._1, pair._2))
})
CourseSearchClickCountDAO.save(list)
})
}) ssc.start()
ssc.awaitTermination()
}
}
package com.lin.spark.streaming.project.utils import java.util.Date import org.apache.commons.lang3.time.FastDateFormat /**
* Created by Administrator on 2019/6/6.
*/
object DateUtils { val YYYYMMDDHHMMSS_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss")
val TARGE_FORMAT = FastDateFormat.getInstance("yyyyMMddHHmmss") def getTime(time:String) ={
YYYYMMDDHHMMSS_FORMAT.parse(time).getTime
} def parseToMinute(time:String)={
TARGE_FORMAT.format(new Date(getTime(time)))
} def main(args: Array[String]): Unit = {
println(parseToMinute("2017-10-22 14:46:01"))
}
}
package com.lin.spark.streaming.project.domain case class ClickLog(ip:String, time:String, courseId:Int, statusCode:Int, referer:String)
package com.lin.spark.streaming.project.domain /**
* Created by Administrator on 2019/6/7.
*/
case class CourseClickCount(day_course:String,click_course:Long)
package com.lin.spark.streaming.project.domain /**
* Created by Administrator on 2019/6/7.
*/
case class CourseSearchClickCount(day_search_course:String, click_count:Long)
package com.lin.spark.streaming.project.dao import com.lin.spark.project.utils.HBaseUtils
import com.lin.spark.streaming.project.domain.CourseClickCount
import org.apache.hadoop.hbase.client.Get
import org.apache.hadoop.hbase.util.Bytes import scala.collection.mutable.ListBuffer /**
* Created by Administrator on 2019/6/7.
*/
object CourseClickCountDAO { val tableName = "lin_course_clickcount"
val cf = "info"
val qualifer = "click_count" def save(list:ListBuffer[CourseClickCount]):Unit={
val table =HBaseUtils.getInstance().getTable(tableName)
for (ele <- list){
table.incrementColumnValue(Bytes.toBytes(ele.day_course),
Bytes.toBytes(cf),
Bytes.toBytes(qualifer),
ele.click_course)
}
} def count(day_course:String):Long={
val table = HBaseUtils.getInstance().getTable(tableName)
val get = new Get(Bytes.toBytes(day_course))
val value = table.get(get).getValue(cf.getBytes,qualifer.getBytes)
if(value == null){
0L
}else{
Bytes.toLong(value)
}
} def main(args: Array[String]): Unit = {
val list = new ListBuffer[CourseClickCount]
list.append(CourseClickCount("20190606",99))
list.append(CourseClickCount("20190608",89))
list.append(CourseClickCount("20190609",100))
// save(list)
println(count("20190609"))
}
}
package com.lin.spark.streaming.project.dao import com.lin.spark.project.utils.HBaseUtils
import com.lin.spark.streaming.project.domain.{CourseClickCount, CourseSearchClickCount}
import org.apache.hadoop.hbase.client.Get
import org.apache.hadoop.hbase.util.Bytes import scala.collection.mutable.ListBuffer /**
* Created by Administrator on 2019/6/7.
*/
object CourseSearchClickCountDAO { val tableName = "lin_course_search_clickcount"
val cf = "info"
val qualifer = "click_count" def save(list:ListBuffer[CourseSearchClickCount]):Unit={
val table =HBaseUtils.getInstance().getTable(tableName)
for (ele <- list){
table.incrementColumnValue(Bytes.toBytes(ele.day_search_course),
Bytes.toBytes(cf),
Bytes.toBytes(qualifer),
ele.click_count)
}
} def count(day_course:String):Long={
val table = HBaseUtils.getInstance().getTable(tableName)
val get = new Get(Bytes.toBytes(day_course))
val value = table.get(get).getValue(cf.getBytes,qualifer.getBytes)
if(value == null){
0L
}else{
Bytes.toLong(value)
}
} def main(args: Array[String]): Unit = {
val list = new ListBuffer[CourseSearchClickCount]
list.append(CourseSearchClickCount("20190606_www.baidu.com_99",99))
list.append(CourseSearchClickCount("20190608_www.bing.com_89",89))
list.append(CourseSearchClickCount("20190609_www.csdn.net_100",100))
save(list)
// println(count("20190609"))
}
}
日志=>flume=>kafka=>spark streaming=>hbase的更多相关文章
- flume+kafka+spark streaming整合
1.安装好flume2.安装好kafka3.安装好spark4.流程说明: 日志文件->flume->kafka->spark streaming flume输入:文件 flume输 ...
- 基于Kafka+Spark Streaming+HBase实时点击流案例
背景 Kafka实时记录从数据采集工具Flume或业务系统实时接口收集数据,并作为消息缓冲组件为上游实时计算框架提供可靠数据支撑,Spark 1.3版本后支持两种整合Kafka机制(Receiver- ...
- Kafka:ZK+Kafka+Spark Streaming集群环境搭建(十)安装hadoop2.9.0搭建HA
如何搭建配置centos虚拟机请参考<Kafka:ZK+Kafka+Spark Streaming集群环境搭建(一)VMW安装四台CentOS,并实现本机与它们能交互,虚拟机内部实现可以上网.& ...
- Kafka:ZK+Kafka+Spark Streaming集群环境搭建(二十一)NIFI1.7.1安装
一.nifi基本配置 1. 修改各节点主机名,修改/etc/hosts文件内容. 192.168.0.120 master 192.168.0.121 slave1 192.168.0.122 sla ...
- Kafka:ZK+Kafka+Spark Streaming集群环境搭建(十一)定制一个arvo格式文件发送到kafka的topic,通过Structured Streaming读取kafka的数据
将arvo格式数据发送到kafka的topic 第一步:定制avro schema: { "type": "record", "name": ...
- Kafka:ZK+Kafka+Spark Streaming集群环境搭建(九)安装kafka_2.11-1.1.0
如何搭建配置centos虚拟机请参考<Kafka:ZK+Kafka+Spark Streaming集群环境搭建(一)VMW安装四台CentOS,并实现本机与它们能交互,虚拟机内部实现可以上网.& ...
- Kafka:ZK+Kafka+Spark Streaming集群环境搭建(八)安装zookeeper-3.4.12
如何搭建配置centos虚拟机请参考<Kafka:ZK+Kafka+Spark Streaming集群环境搭建(一)VMW安装四台CentOS,并实现本机与它们能交互,虚拟机内部实现可以上网.& ...
- Kafka:ZK+Kafka+Spark Streaming集群环境搭建(三)安装spark2.2.1
如何搭建配置centos虚拟机请参考<Kafka:ZK+Kafka+Spark Streaming集群环境搭建(一)VMW安装四台CentOS,并实现本机与它们能交互,虚拟机内部实现可以上网.& ...
- demo2 Kafka+Spark Streaming+Redis实时计算整合实践 foreachRDD输出到redis
基于Spark通用计算平台,可以很好地扩展各种计算类型的应用,尤其是Spark提供了内建的计算库支持,像Spark Streaming.Spark SQL.MLlib.GraphX,这些内建库都提供了 ...
随机推荐
- Javascript 数组的一些操作
(1) shift 删除原数组第一项,并返回删除元素的值:如果数组为空则返回undefined var a = [1,2,3,4,5]; var b = a.shift(); //a:[2,3,4, ...
- Center os 用户环境变量
vi ~/.bash_profile进入用户环境变量设置 export JAVA_HOME=/usr/java/jdk1.7.0_76export JAVA_BIN=$JAVA_HOME/binexp ...
- 如何改变string中的字符值?
string本身是不可变的,因此要改变string中字符,需要如下操作: str := “hello world” s := []byte(str) s[] = ‘o’ str = string(s) ...
- 【串线篇】Mybatis缓存简介
缓存:暂时的存储一些数据:加快系统的查询速度... CPU: 主频:4-2.7GHZ 内存:4G-8G 1333MHZ 2166MHZ CPU:一级缓存(4MB):二级缓存 (16MB); ...
- centos7安装nginx并配置web前端环境。
1.安装nginx -sudo yum install nginx 2.启动nginx - systemctl start nginx 3.修改nginx路径配置,/etc/nginx/nginx.c ...
- 苹果推出了AI手机,打造一款高度个性化的设备
在今年苹果的WWDC 2018上,一些人认为今年会因为软件专注而缺乏新的MacBook和iPad而感到无聊,该公司宣布,iOS12的推出可能是迄今为止最重要的操作系统更新.一系列Siri增强功能,Ap ...
- STM32 通用定时器好文章收藏
https://blog.csdn.net/fengshuiyue/article/details/79150724 单片机入门学习十三 STM32单片机学习十 通用定时器 里面写的挺不错,图文并茂, ...
- 【leetcode】623. Add One Row to Tree
题目如下: Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with ...
- js 自定义map
<script> function HashMap(){this.map = {};} HashMap.prototype = { put : function(key, value){ ...
- git常用操作命令1
1. 本地库初始化操作 命令: git init 效果: Initialized empty Git repository in E:/ws/git/ws/.git/ 会在当前目录(E:/ws/git ...