Spark-Streaming

WordCount案例

添加依赖

<?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">

<parent>

<artifactId>Sparkes</artifactId>

<groupId>org.example</groupId>

<version>1.0-SNAPSHOT</version>

</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>Sparkes-core</artifactId>

<properties>

<maven.compiler.source>8</maven.compiler.source>

<maven.compiler.target>8</maven.compiler.target>

</properties>

<dependencies>

<dependency>

<groupId>org.apache.spark</groupId>

<artifactId>spark-core_2.12</artifactId>

<version>3.0.0</version>

</dependency>

<dependency>

<groupId>org.apache.spark</groupId>

<artifactId>spark-streaming_2.12</artifactId>

<version>3.0.0</version>

</dependency>

</dependencies>

</project>

代码

import org.apache.spark.SparkConf

import org.apache.spark.streaming.{Seconds, StreamingContext}

object SparkStreaming {

def main(args: ArrayString): Unit = {

// 创建 SparkConf 对象,设置运行模式和应用名称

val sparkConf = new SparkConf().setMaster("local\*").setAppName("streaming")

// 创建 StreamingContext 对象,设置批处理间隔为 3 秒

val ssc = new StreamingContext(sparkConf, Seconds (3))

// 从指定的套接字地址接收文本流数据

val lineStreams = ssc.socketTextStream("node01", 9999)

// 将每行文本拆分为单词

val wordStreams = lineStreams.flatMap(_.split(" "))

// 将每个单词映射为 (单词, 1) 的键值对

val wordAndOneStreams = wordStreams.map((_, 1))

// 对相同单词的计数进行累加

val wordAndCountStreams = wordAndOneStreams.reduceByKey(_ + _)

// 打印每个批次的单词计数结果

wordAndCountStreams.print()

// 启动 StreamingContext

ssc.start()

// 等待 StreamingContext 终止

ssc.awaitTermination()

}

}

相关推荐
皮皮学姐分享-ppx26 分钟前
政府绿色采购数据库(2015-2024.3)
大数据·网络·数据库·人工智能·制造
无忧智库4 小时前
某公共大数据资源中心平台建设项目可行性研究方案(PPT)
大数据
诗词在线6 小时前
求推荐飞花令
大数据·人工智能·python
湘美书院--湘美谈教育6 小时前
湘美谈教育AI系列经验集锦:赋能整理聊斋志异大寓言
大数据·人工智能·深度学习·神经网络·机器学习
jrjrgood7 小时前
现货黄金和黄金期货的区别有哪些?如何投资?
大数据·人工智能·区块链
清辞8538 小时前
Coze从入门到实战---第一、二章
大数据·人工智能·学习·语言模型
TomatoStudy8 小时前
IT职业教育AI落地与实训体系建设复盘——以职坐标模式为例
大数据·人工智能
Java 码思客8 小时前
【ElasticSearch从入门到架构师】第1章:ElasticSearch 核心认知与行业定位
大数据·elasticsearch·搜索引擎
cui17875689 小时前
物业费收缴困局的破题之路:2026年社区商业逻辑的底层重构
大数据·数据库·人工智能
2501_933670799 小时前
大数据在校实训项目一般做什么类型内容
大数据