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博客

相关推荐
知行产研几秒前
红二矿:深耕能源融合与智能重构 探索矿山低碳高效转型新路径
大数据·重构·能源
石山代码1 分钟前
Python 进阶学习指南
开发语言·python
lichenyang4533 分钟前
鸿蒙电商 Demo v2:真实商品接口 + 支付/订单闭环 + 收藏功能,外加一个 ArkUI V2 @Builder 响应式断链的硬核坑
前端·后端
前端的阶梯3 分钟前
如何节省你的token,请看CodeGraph
前端·人工智能·后端
用户83562907805118 分钟前
Python 在 PowerPoint 中创建箱形图
后端·python
万少39 分钟前
产品原型不用从零画 -GPT 出图,Gemini 生成 HTML
前端·javascript·后端
xiaoshuaishuai81 小时前
C# 多线程之间对比
java·开发语言·c#
小宇子2B1 小时前
一个 Vec 的数据到底在内存哪:栈、堆,和它们相向而行的真相
后端·编程语言
189228048611 小时前
NV086固态MT29F16T08EWLCHD8-TES:C
大数据·服务器·人工智能·科技·缓存
程序员黑豆2 小时前
全新系列开启:AI 全栈开发
前端·后端·全栈