sparkstreamnig实时处理入门

1.2 SparkStreaming实时处理入门

1.2.1 工程创建

导入maven依赖

Go 复制代码
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.12</artifactId>
    <version>3.1.2</version>
</dependency>
<dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming-kafka-0-10_2.12</artifactId>
            <version>3.1.2</version>
        </dependency>
1.2.2 入口类StreamingContext
复制代码
SparkStreaming中的入口类,称之为StreamingContext,但是底层还是得需要依赖SparkContext。
复制代码
object SparkStreamingWordCountOps {
    def main(args: Array[String]): Unit = {
        /*
            StreamingContext的初始化,需要至少两个参数,SparkConf和BatchDuration
            SparkConf不用多说
            batchDuration:提交两次作业之间的时间间隔,每次会提交一个DStream,将数据转化batch--->RDD
            所以说:sparkStreaming的计算,就是每隔多长时间计算一次数据
         */
        val conf = new SparkConf()
                    .setAppName("SparkStreamingWordCount")
                    .setMaster("local[*]")
        val duration = Seconds(2)
        val ssc = new StreamingContext(conf, duration) //批次
​
        //业务
        
        
        //为了执行的流式计算,必须要调用start来启动
        ssc.start()
        //为了不至于start启动程序结束,必须要调用awaitTermination方法等待程序业务完成之后调用stop方法结束程序,或者异常
        ssc.awaitTermination()
    }
}
1.2.3 业务编写

SparkStreaming是一个流式计算的计算引擎,那么 就模拟一个对流式数据进行单词统计

代码实现

复制代码
package com.qianfeng.sparkstreaming
​
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Durations, StreamingContext}
​
/**
 * sparkStreaming的流程序
 */
object Demo01_SparkStreaming_WC {
  def main(args: Array[String]): Unit = {
    //1、获取streamingcontext
    val conf = new SparkConf()
      .setAppName("streaming wc")
      .setMaster("local[*]")
    val sc = new StreamingContext(conf, Durations.seconds(2)) //微批次微2s
    //2、初始化数据
    val ds = sc.socketTextStream("qianfeng01", 6666)
    //3、对数据进行操作
    val sumDS = ds.flatMap(_.split(" "))
      #判断H开头 5位
      .filter(x=>x.startsWith("H") && x.length == 5)
      .map((_, 1))
      .reduceByKey(_ + _)
    //4、对数据做输出
    sumDS.print()
​
    //5、开启sc
    sc.start()
    //6、等待结束  --- 实时不能停止
    sc.awaitTermination()
  }
}

使用netcat进行测试(如果没有请先安装,有则忽略如下)

需要在任意一台节点上安装工具:

复制代码
[root@qianfeng01 home]# yum install -y nc

启动监听端口:

复制代码
[root@qianfeng01 home]# nc -lk 6666
hello nihao
nihao hello
hi
hello nihao

Guff_hys_python数据结构,大数据开发学习,python实训项目-CSDN博客

相关推荐
SamDeepThinking2 分钟前
我们当年是如何真实落地BFF的?
java·后端·架构
Asmewill9 分钟前
Centos系统docker时间同步方案
后端
阿正的梦工坊10 分钟前
【Rust】09-泛型、Trait 与生命周期基础
开发语言·rust·c#
用户83562907805119 分钟前
使用 Python 操作 Word 评论和回复
后端·python
心在飞扬30 分钟前
CentOS + Node.js 全套部署命令
后端
阿正的梦工坊33 分钟前
【Rust】07-错误处理:Option、Result 与 ? 运算符
开发语言·算法·rust
Zella折耳根38 分钟前
复习篇-继承和接口
java·开发语言·python
z落落41 分钟前
C# 事件(Event)+自定义带参数事件例子
开发语言·分布式·c#
FlYFlOWERANDLEAF41 分钟前
DevExpress Office File API使用记录
开发语言·c#·devoffice