flink简单应用: scala编写wordcount

在ida中创建maven项目,配置scala环境,调用flink-streaming-scala的api

1, flink: DataStream applications

a,配置pom.xml

  <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-scala_2.11</artifactId>
            <version>1.7.2</version>
  </dependency>

b,调用flink 流计算 api

socket流,实时wordcount: keyby(“字段名1”).sum(“字段名1”)

import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time

object Flink1 {
  // Data type for words with count
  case class WordWithCount(word: String, count: Long)

  def main(args: Array[String]): Unit = {
    // 获取执行器的环境
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //获取数据: 从socket中获取
    val textDataStream = env.socketTextStream("127.0.0.1", 8888, '\n')
    val tupDataStream = textDataStream.flatMap(_.split(" ")).map(WordWithCount(_,1))

    //groupby: 按照指定的字段聚合
    val windowDstram = tupDataStream.keyBy("word").timeWindow(Time.seconds(5), Time.seconds(1))//窗口bsize=5秒, slid=1s
    windowDstram.sum("count").print()

    //启动执行器,执行程序
    env.execute("Socket Window WordCount")
  }
}

/**
#---------------启动nc: 输入数据
wang@wang-pc:/soft/flink/bin$ nc -lk 8888
a
*/

/**
#---------------观察程序输出:
> WordWithCount(a,1)
> WordWithCount(a,1)
> WordWithCount(a,1)

> WordWithCount(a,1)
> WordWithCount(a,1)
*/

2, flink: DataSet applications

a,配置pom.xml

 <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-scala_2.11</artifactId>
        <version>1.7.2</version>
 </dependency>

b,调用flink 批处理api

读取文本文件,groupBy(元组字段1).sum(元组字段1)

import org.apache.flink.api.scala._

object Flink2 {
  def main(args: Array[String]): Unit = {
    //获取执行器env
    val env = ExecutionEnvironment.getExecutionEnvironment

    //读取文件中的数据
    val text = env.readTextFile("/home/wang/a.txt")

    //对数据过滤,加工处理
    val counts = text.flatMap { _.toLowerCase.split("\\W+"). filter { _.nonEmpty } }
      .map { (_, 1) }
      .groupBy(0)
      .sum(1)

    //action: 触发任务
    counts.print()
    counts.writeAsText("flink-wc5")
    env.execute("text WordCount")
  }
}

/**
#---------------文件中的数据:
wang@wang-pc:/soft/flink$ cat ~/a.txt
a,b
b,b
c,c

#---------------程序输出结果:
(a,1)
(b,3)
(c,2)
  */
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

根哥的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值