基础数据类型
Flink支持Java和Scala中所常见的数据类型
- Long
val numbers: DataStream[Long] = env.fromElements(1L, 2L, 3L, 4L) numbers.map( n => n + 1 )
- 元组
val persons: DataStream[(String, Integer)] = env.fromElements( ("Adam", 17), ("Sarah", 23) ) persons.filter(p => p._2 > 18)
- 样例类
case class Person(name: String, age: Int) val persons: DataStream[Person] = env.fromElements( Person("Adam", 17), Person("Sarah", 23) ) persons.filter(p => p.age > 18)
- 简单类
public class Person { public String name; public int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } } DataStream<Person> persons = env.fromElements( new Person("Alex", 42), new Person("Wendy", 23));
- Flink 对 Java 和 Scala(ArrayList,HashMap,Enum等)也支持
实现UDF函数-更细粒度的控制流
函数类(Function classes)
Flink暴露了所有udf函数的接口(实现方式为接口或抽象类) 例如: MapFunction、FilterFunction、ProcessFunction
- 实现FilterFunction接口
class FilterFilter extends FilterFunction[String] { override def filter(value: String): Boolean = { value.contains("flink") } } val flinkTweets = tweets.filter(new FlinkFilter)
- 将函数实现成匿名类
val flinkTweets = tweets.filter( new RichFilterFunction[String] { override def filter(value: String): Boolean = { value.contains("flink") } } )
- 字符串作为参数传进去
val tweets: DataStream[String] = ... val flinkTweets = tweets.filter(new KeywordFilter("flink")) class KeywordFilter(keyWord: String) extends FilterFunction[String] { override def filter(value: String): Boolean = { value.contains(keyWord) } }
匿名函数(Lamdba Functions)
val tweets: DataStream[String] = ... val flinkTweets = tweets.filter(_.contains("flink"))
// _ .id 代表 data => data.id dataStream.filter( _.id.statWith("sensor_1")).print
副函数
函数类接口 所有的Flink函数类都有Rich版本 与常规函数区别: 可以获取运行时上下文 并拥有一些生命周期方法 可以实现更加复杂的功能 a、 RichMapFunction b、 RichFlatMapFunction c、 RichFilterFunction 生命周期: a、open() 是 rich fuction初始化方法 当一个算子例如map或filter被调用之前 open会被调用 b、close方法 是生命周期中的最后一个调用方法 做一些清理工作 c、getRuntimeContext方法 提供了函数的RuntimeContext的一些信息 例如函数的执行并行度、任务的名字以及state状态
- 代码
class MyFlatMap extends RichFlatMapFunction[Int, (Int, Int)] { var subTaskIndex = 0 override def open(configuration: Configuration): Unit = { subTaskIndex = getRuntimeContext.getIndexOfThisSubtask // 以下可以做一些初始化工作 , 例如建立一个和 HDFS 的连接 } override def flatMap(in: Int, out: Collector[(Int, Int)]): Unit = { if (in % 2 == subTaskIndex) { out.collect((subTaskIndex, in)) } } override def close(): Unit = { // 以下做一些清理工作,例如断开和 HDFS 的连接。 } }