Flink之广播状态模式

本文介绍了Apache Flink中广播状态的使用,包括BroadcastProcessFunction和KeyedBroadcastProcessFunction的用法。通过示例展示了如何连接两个流并利用广播状态进行匹配逻辑。强调了广播状态模式的重要注意事项,如无跨任务通信、状态更新的一致性和事件顺序的差异性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.提供的API

为了展示所提供的API,我们将以一个示例开始,然后介绍其完整功能。作为正在运行的示例,我们将使用这样的情况,其中有一系列不同颜色和形状的对象,并且我们希望找到遵循某种模式的相同颜色的对象对,例如矩形后跟三角形。我们假设这组有趣的模式会随着时间而演变。

在此示例中,第一个流将包含Item带有Color和Shape属性的type元素。另一个流将包含Rules。

从流开始Items,我们只需要键入它的Color,因为我们要对相同颜色的。这将确保相同颜色的元素最终出现在同一台物理计算机上。

// key the items by color
KeyedStream<Item, Color> colorPartitionedStream = itemStream
                        .keyBy(new KeySelector<Item, Color>(){
   ...});

移至Rules,应将包含它们的流广播到所有下游任务,并且这些任务应将它们存储在本地,以便它们可以针对所有传入的Items进行评估。下面的代码段将使用广播规则流,并且使用提供的MapStateDescriptor,将创建存储规则的广播状态。

// a map descriptor to store the name of the rule (string) and the rule itself.
MapStateDescriptor<String, Rule> ruleStateDescriptor = new MapStateDescriptor<>(
			"RulesBroadcastState",
			BasicTypeInfo.STRING_TYPE_INFO,
			TypeInformation.of(new TypeHint<Rule>() {
   }));
		
// broadcast the rules and create the broadcast state
BroadcastStream<Rule> ruleBroadcastStream = ruleStream
                        .broadcast(ruleStateDescriptor);

最后,根据Rules中的Item流中的传入元素评估,我们需要:

  1. 连接两个流。
  2. 指定匹配检测逻辑。

BroadcastStream可以通过调用connect()来将流(键控或非键控)与非广播流(以键BroadcastStream为参数)进行连接。我们可以调用特殊类型CoProcessFunction的process()方法,这将返回一个BroadcastConnectedStream。该函数将包含我们的匹配逻辑。函数的确切类型取决于非广播流的类型:

  1. 如果输入了密码,则该函数为KeyedBroadcastProcessFunction。
  2. 如果它是非键,则该函数为BroadcastProcessFunction。

鉴于我们的非广播流已加密,以下代码段包含上述调用:

注意:应该在非广播流上调用connect,并以BroadcastStream作为参数。
DataStream<String> output = colorPartitionedStream
   .connect(ruleBroadcastStream)
    .process(
        
        // type arguments in our KeyedBroadcastProcessFunction represent: 
        //   1. the key of the keyed stream
        //   2. the type of elements in the non-broadcast side
        //   3. the type of 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值