【Spark】SparkStreaming从不同基本数据源读取数据
文章目录
基本数据源
文件数据源
注意事项
1.SparkStreaming不支持监控嵌套目录
2.文件进入dataDirectory(受监控的文件夹)需要通过移动或者重命名实现
3.一旦文件移动进目录,则不能再修改,即使修改也不会读取修改后的数据
步骤
一、创建maven工程并导包
<properties>
<scala.version>2.11.8</scala.version>
<spark.version>2.2.0</spark.version>
</properties>
<dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>${spark.version}</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>${spark.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-hive_2.11</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/scala</sourceDirectory>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<!-- <verbal>true</verbal>-->
</configuration>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
<configuration>
<args>
<arg>-dependencyfile</arg>
<arg>${project.build.directory}/.scala_dependencies</arg>
</args>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass></mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
二、在HDFS创建目录,并上传要做测试的数据
cd /export/servers/
vim wordcount.txt
hello world
abc test
hadoop hive
HDFS上创建目录
hdfs dfs -mkdir /stream_data
hdfs dfs -put wordcount.txt /stream_data
三、开发SparkStreaming代码
package cn.itcast.sparkstreaming.demo1
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Seconds, StreamingContext}
object getHdfsFiles {
// 自定义updateFunc函数
/**
* updateFunc需要两个参数
*
* @param newValues 新输入数据计数累加的值
* @param runningCount 历史数据计数累加完成的值
* @return 返回值是Option
*
* Option是scala中比较特殊的类,是some和none的父类,主要为了解决null值的问题
*/
def updateFunc(newValues: Seq[Int], runningCount: Option[Int]): Option[Int] = {
val finalResult: Int = newValues.sum + runningCount.getOrElse(0)
Option(finalResult)
}
def main(args: Array[String]): Unit = {
//获取SparkConf
val sparkConf: SparkConf = new SparkConf().setAppName("getHdfsFiles_to_wordcount").setMaster("local[6]").set("spark.driver.host", "localhost")
// 获取SparkContext
val sparkContext = new SparkContext(sparkConf)
// 设置日志级别
sparkContext.setLogLevel("WARN")
// 获取StreamingContext
val streamingContext = new StreamingContext(sparkContext, Seconds(5))
// 将历史结果都保存到一个路径下
streamingContext.checkpoint("./stream.check")
// 读取HDFS上的文件
val fileStream: DStream[String] = streamingContext.textFileStream("hdfs://node01:8020/stream_data")
// 对读取到的文件进行计数操作
val flatMapStream: DStream[String] = fileStream.flatMap(x => x.split(" "))
val wordAndOne: DStream[(String, Int)] = flatMapStream.map(x => (x, 1))
// reduceByKey不会将历史消息的值进行累加,所以需要用到updateStateByKey,需要的参数是updateFunc,需要自定义
val byKey: DStream[(String, Int)] = wordAndOne.updateStateByKey(updateFunc)
//输出结果
byKey.print()
streamingContext.start()
streamingContext.awaitTermination()
}
}
四、运行代码后,往HDFS文件夹上传文件

五、控制台输出结果
-------------------------------------------
Time: 1586856345000 ms
-------------------------------------------
-------------------------------------------
Time: 1586856350000 ms
-------------------------------------------
-------------------------------------------
Time: 1586856355000 ms
-------------------------------------------
(abc,1)
(world,1)
(hadoop,1)
(hive,1)
(hello,1)
(test,1)
-------------------------------------------
Time: 1586856360000 ms
-------------------------------------------
(abc,1)
(world,1)
(hadoop,1)
(hive,1)
(hello,1)
(test,1)
-------------------------------------------
Time: 1586856365000 ms
-------------------------------------------
(abc,1)
(world,1)
(hadoop,1)
(hive,1)
(hello,1)
(test,1)
-------------------------------------------
Time: 1586856370000 ms
-------------------------------------------
(abc,2)
(world,2)
(hadoop,2)
(hive,2)
(hello,2)
(test,2)
-------------------------------------------
Time: 1586856375000 ms
-------------------------------------------
(abc,2)
(world,2)
(hadoop,2)
(hive,2)
(hello,2)
(test,2)
自定义数据源
步骤
一、使用nc工具给指定端口发送数据
nc -lk 9999
二、开发代码
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}
object CustomReceiver {
/**
* 自定义updateFunc函数
* @param newValues
* @param runningCount
* @return
*/
def updateFunc(newValues:Seq[Int], runningCount:Option[Int]):Option[Int] = {
val finalResult: Int = newValues.sum + runningCount.getOrElse(0)
Option(finalResult)
}
def main(args: Array[String]): Unit = {
// 获取SparkConf
val sparkConf: SparkConf = new SparkConf().setAppName("CustomReceiver").setMaster("local[6]").set("spark.driver.host", "localhost")
// 获取SparkContext
val sparkContext = new SparkContext(sparkConf)
sparkContext.setLogLevel("WARN")
// 获取StreamingContext
val streamingContext = new StreamingContext(sparkContext, Seconds(5))
streamingContext.checkpoint("./stream_check")
// 读取自定义数据源的数据
val stream: ReceiverInputDStream[String] = streamingContext.receiverStream(new MyReceiver("node01", 9999))
// 对数据进行切割、计数操作
val mapStream: DStream[String] = stream.flatMap(x => x.split(" "))
val wordAndOne: DStream[(String, Int)] = mapStream.map((_, 1))
val byKey: DStream[(String, Int)] = wordAndOne.updateStateByKey(updateFunc)
// 输出结果
byKey.print()
streamingContext.start()
streamingContext.awaitTermination()
}
}
import java.io.{BufferedReader, InputStream, InputStreamReader}
import java.net.Socket
import java.nio.charset.StandardCharsets
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.receiver.Receiver
class MyReceiver(host:String,port:Int) extends Receiver[String](StorageLevel.MEMORY_AND_DISK_2){
/**
* 自定义receive方法接收socket数据,并调用store方法将数据保存起来
*/
private def receiverDatas(): Unit ={
// 接收socket数据
val socket = new Socket(host, port)
// 获取socket数据输入流
val stream: InputStream = socket.getInputStream
//通过BufferedReader ,将输入流转换为字符串
val reader = new BufferedReader(new InputStreamReader(stream,StandardCharsets.UTF_8))
var line: String = null
//判断读取到的数据不为空且receiver没有被停掉时
while ((line = reader.readLine()) != null && !isStopped()){
store(line)
}
stream.close()
socket.close()
reader.close()
}
/**
* 重写onStart和onStop方法,主要是onStart,onStart方法会被反复调用
*/
override def onStart(): Unit = {
// 启动通过连接接收数据的线程
new Thread(){
//重写run方法
override def run(): Unit = {
// 定义一个receiverDatas接收socket数据
receiverDatas()
}
}
}
// 停止结束的时候被调用
override def onStop(): Unit = {
}
}
RDD队列
步骤
一、开发代码
package cn.itcast.sparkstreaming.demo3
import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import scala.collection.mutable
object QueneReceiver {
def main(args: Array[String]): Unit = {
//获取SparkConf
val sparkConf: SparkConf = new SparkConf().setMaster("local[6]").setAppName("queneReceiver").set("spark.driver.host", "localhost")
//获取SparkContext
val sparkContext = new SparkContext(sparkConf)
sparkContext.setLogLevel("WARN")
//获取StreamingContext
val streamingContext = new StreamingContext(sparkContext, Seconds(5))
val queue = new mutable.SynchronizedQueue[RDD[Int]]
// 需要参数 queue: Queue[RDD[T]]
val inputStream: InputDStream[Int] = streamingContext.queueStream(queue)
// 对DStream进行操作
val mapStream: DStream[Int] = inputStream.map(x => x * 2)
mapStream.print()
streamingContext.start()
//定义一个RDD队列
for (x <- 1 to 100){
queue += streamingContext.sparkContext.makeRDD(1 to 10)
Thread.sleep(3000)
}
streamingContext.awaitTermination()
}
}
【Spark】SparkStreaming从不同基本数据源读取数据的更多相关文章
- spark SQL (五)数据源 Data Source----json hive jdbc等数据的的读取与加载
1,JSON数据集 Spark SQL可以自动推断JSON数据集的模式,并将其作为一个Dataset[Row].这个转换可以SparkSession.read.json()在一个Dataset[Str ...
- spark SQL(三)数据源 Data Source----通用的数据 加载/保存功能
Spark SQL 的数据源------通用的数据 加载/保存功能 Spark SQL支持通过DataFrame接口在各种数据源上进行操作.DataFrame可以使用关系变换进行操作,也可以用来创建临 ...
- echarts通过ajax向服务器发送post请求,servlet从数据库读取数据并返回前端
1.echarts的官网上的demo,都是直接写死的随机数据,没有和数据库的交互,所以就自己写了一下,ok,我们开始一步一步走一遍整个流程吧. 就以官网最简单的那个小demo来做修改吧.官网上的小de ...
- 2、 Spark Streaming方式从socket中获取数据进行简单单词统计
Spark 1.5.2 Spark Streaming 学习笔记和编程练习 Overview 概述 Spark Streaming is an extension of the core Spark ...
- 创建spark_读取数据
在2.0版本之前,使用Spark必须先创建SparkConf和SparkContext,不过在Spark2.0中只要创建一个SparkSession就够了,SparkConf.SparkContext ...
- kettle7.1无法从Mongo中读取数据
今天使用kettle读取mongo数据库时,刚开始一直无法读取数据: 在配置项中偶然选择了一个nearest然后成功了,麻蛋. 然后百度查询了下Read Reference是干嘛的,原来是读取源的模式 ...
- Ado.Net基础拾遗一:读取数据
从数据库中读取数据: 使用DataReader对象从数据库中读取数据 首先需要添加几个命名空间 //需要添加的命名空间 using System.Configuration; using System ...
- Spark SQL - 对大规模的结构化数据进行批处理和流式处理
Spark SQL - 对大规模的结构化数据进行批处理和流式处理 大体翻译自:https://jaceklaskowski.gitbooks.io/mastering-apache-spark/con ...
- Power BI 的数据源及数据刷新
Power BI 目前可以连接超过100种数据源,包含常见的各种数据库,文件,数据仓库,云等等. 不同的数据源支持不同的连接方式,通常来讲,Power BI 支持两种数据连接方式: 导入(import ...
随机推荐
- MVC学习的心路历程
2020/4/17 之前接触过三层架构,但是没有接触过mvc,所以有点蒙,所以现在在一步步构建思路. 1.了解MVC的发展,做一个简单的项目.
- T - Nash Matrix CodeForces - 1316D
题意: 输入n行数,没行由2*n个数,表示一个坐标(x,y). 如果x和y==-1表示从该点(i,j)出发,按照构造的前移动不会停下. 否则就要到点(x,y)处停下. 题解: 首先处理-1 枚举每个 ...
- CodeForces - 913C (贪心)
点完菜,他们发现好像觉得少了点什么? 想想马上就要回老家了某不愿透露姓名的林姓学长再次却陷入了沉思......... 他默默的去前台打算点几瓶二锅头. 他发现菜单上有n 种不同毫升的酒. 第 i 种有 ...
- position的用法(top, bottom, left, right 四个定位属性配合进行使用)
一般情况下 页面元素的定位方式是根据文档流也就是说默认的从上到下,从左到右的方式进行排列的,而将元素从文档流脱离出来显示的方式有两种,一种是 position 定位另一种是float 浮动,这里我们详 ...
- 进程管理工具 Supervisor
要想在终端后台常驻进程,首先想到的是在命令后加 & 符号,来达到隐藏程序在后台的目的,尽管看起来进程已经在后台运行了,实际上终端会话关闭时进程还是会被 kill 掉,这种问题一般是采用搭配 n ...
- BypassUAC
BypassUAC 本篇主要介绍如何以ICMLuaUtil方式BypassUAC,主要内容如下: 过掉UAC提示框的方法总结 UACME项目 什么类型的COM interface可以利用? 如何快速找 ...
- Python pandas库159个常用方法使用说明
Pandas库专为数据分析而设计,它是使Python成为强大而高效的数据分析环境的重要因素. 一.Pandas数据结构 1.import pandas as pd import numpy as np ...
- php的echo 和 return的区别
来源:https://blog.csdn.net/ljfphp/article/details/76718635 项目中碰到的问题,本来是想在控制器直接return $xml的($xml是一段xml格 ...
- 2019-2020-1 20199310《Linux内核原理与分析》第十一周作业
1.问题描述 在一个capability系统中,当一个程序运行时,对应的线程会初始化一系列capabilities(令牌).当线程尝试访问某个对象时,操作系统会检查该线程的capabilities,并 ...
- web 之 session
Session? 在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占一个session对象(默认情况下).因此,在需要保存用户数据时,服务器程序可以 ...