当前位置:网站首页>Flink从入门到真香(3、从集合和文件中读取数据)

Flink从入门到真香(3、从集合和文件中读取数据)

2020-11-08 12:06:35 osc_neocf7df

关于环境准备可以参考: https://blog.51cto.com/mapengfei/2546985

从集合中读取数据

新建包,com.mafei.apitest,新建一个scala Object类,

package com.mafei.apitest

import org.apache.flink.api.scala.createTypeInformation
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment

//获取传感器数据

case class SensorReading(id: String,timestamp: Long, temperature: Double)
object SourceTest {

  def main(args: Array[String]): Unit = {
    //创建执行环境
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    // 1、从集合中读取数据
    val dataList = List(
      SensorReading("sensor1",1603766281,41),
      SensorReading("sensor2",1603766282,42),
      SensorReading("sensor3",1603766283,43),
      SensorReading("sensor4",1603766284,44)
    )

    val stream1 = env.fromCollection(dataList)

    stream1.print()

    //执行
    env.execute(" source test")
  }

}

代码目录图:
Flink从入门到真香(3、从集合和文件中读取数据)
运行效果
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
2> SensorReading(sensor3,1603766283,43.0)
4> SensorReading(sensor1,1603766281,41.0)
3> SensorReading(sensor4,1603766284,44.0)
1> SensorReading(sensor2,1603766282,42.0)








从文件读取数据

和第一步一样,新建包,com.mafei.apitest,新建一个scala Object类,

package com.mafei.apitest

import org.apache.flink.api.scala.createTypeInformation
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment

//获取传感器数据

case class SensorReading(id: String,timestamp: Long, temperature: Double)
object SourceTest {

  def main(args: Array[String]): Unit = {
    //创建执行环境
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    //从文件中读取数据
    val stream2= env.readTextFile("/opt/java2020_study/maven/flink1/src/main/resources/sensor.txt")

    stream2.print()

    //执行
    env.execute(" source test")
  }

}

在resources目录下新建sensor.txt,写入以下内容
sensor1,1603766281,41
sensor2,1603766282,42
sensor3,1603766283,43
sensor4,1603766284,44



代码结构图:
Flink从入门到真香(3、从集合和文件中读取数据)

代码运行效果:
1> sensor1,1603766281,41
1> sensor2,1603766282,42
2> sensor3,1603766283,43
3> sensor4,1603766284,44



版权声明
本文为[osc_neocf7df]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4416758/blog/4708099