应用场景
- 实时更新配置,例如:任务在统计3个页面的uv,又要统计另外三个页面的uv,那我是不是可以通过配置的方式,快速实现类似需求
- 实时加载维表,例如:kafka里用户购买的订单信息的binlog,但不知道商品id对应的商品,商品也在不断增加,这个时候我需要加载一个维表来做mapping,此时我不想查寻数据库,那怎么做mapping呢?
- 部分流join场景
简介
简单来说就是流合并,一个流作为广播流,一个流作为数据流,即一个大流,一个小流,广播流会将配置或者维表不定时的广播发布,数据流收到广播流的数据后进行相应的操作。
两种用法,一种有key的DataStream(指的是进行过group操作的),一种无key的DataStream
重写processBroadcastElement将配置进行广播
val state = ctx.getBroadcastState(configStateDescriptor)
state.put(table, config)
重写processElement获取广播数据进行组合
val config: Config = getIndexesConf(ctx, table)
out.collect(indexDocInfos)
使用
final var configBroadcast = new MapStateDescriptor[String, Int]("mb", classOf[String], classOf[Int])
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setParallelism(1)
// 流
val dataStream1: DataStream[String] = env.fromCollection(util.Arrays.asList(
"aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc"
))
// 配置
val dataStream2: BroadcastStream[(String, Int)] = env.fromCollection(util.Arrays.asList(
("aa", 1), ("bb", 2), ("cc", 3)
)).setParallelism(1).broadcast(configBroadcast)
//合关两个数据流
val dataStream: DataStream[String] = dataStream1
.connect(dataStream2)
.process(new BroadcastProcessFunction[String, (String, Int), String] {
override def processBroadcastElement(in2: (String, Int), ctx: BroadcastProcessFunction[String, (String, Int), String]#Context, collector: Collector[String]): Unit = {
val state = ctx.getBroadcastState(configBroadcast)
state.put(in2._1, in2._2)
}
override def processElement(in1: String, ctx: BroadcastProcessFunction[String, (String, Int), String]#ReadOnlyContext, cut: Collector[String]): Unit = {
val broadCastState = ctx.getBroadcastState(configBroadcast)
if (!broadCastState.contains(in1)) {
cut.collect(in1+"123")
} else {
cut.collect(in1+broadCastState.get(in1))
}
}
})
dataStream.print()
env.execute("job");
}
结果,一开始会匹配不上。