Structured Streaming初试

175 篇文章 3 订阅
2 篇文章 0 订阅

本篇博客记录一下自己初次尝试使用Structured Streaming。

首先写 一个程序来监昕网络端口发来的内容,然后进行 WordCount 。

package main.learningbigdata.spark.spark3step

import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession

/**
  * FileName: StructuredStreamingWordCount
  * Author:   hadoop
  * Email:    3165845957@qq.com
  * Date:     19-6-1 下午3:34
  * Description:
  * Structured Streaming例子
  *
  */
object StructuredStreamingWordCount {

  def main(args: Array[String]): Unit = {

    //设置配置
    val conf = new SparkConf()
      .setAppName("StructuredStreamingWordCount")
      .setMaster("local[2]")

    /**
      * 第一步:创建程序入口SparkSession ,并引入spark.implicits._来允许 Scalaobject 隐式转换为DataFrame
      */

    val spark = SparkSession.builder().config(conf).getOrCreate()

    import spark.implicits._

    /**
      * 第二步:创建流。配置从 socket 读取流数据,地址和端口为 localhost: 9999。
      */
    val lines = spark.readStream.format("socket")
      .option("host","localhost")
      .option("port","9999")
      .load()
    /**
      * 第三步:进行单词统计。这里 lines 是 DataFrame ,使用 as[String]给它定义类型转换为
      * Dataset 。 之后在 Dataset 里进行单词统计。
      */
    val words = lines.as[String].flatMap(_.split(" "))

    val wordCount = words.groupBy("value").count()
    /**
      * 第四步:创建查询句柄,定义打印结果方式并启动程序 。 这里使用 write Stream 方法 , 输
      * 出模式为全部输出到控制台。
      */
    val query = wordCount.writeStream.outputMode("complete").format("console").start()
    query.awaitTermination()

    /**
      * 第五步:接下来运行该程序,在 Linux 命令窗口运行 nc-lk 9999 开启 9999 端口 。
      */
  }

}

为了方便就直接在IDE上运行,使用IDEA运行时,需要设置一下运行参数

run -->Edit Configurations...

接下来运行该程序,在 Linux 命令窗口运行 nc-lk 9999 开启 9999 端口。

在IDEA控制台上就能看到wordCount结果了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值