一.提供的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流中的传入元素评估,我们需要:
- 连接两个流。
- 指定匹配检测逻辑。
BroadcastStream可以通过调用connect()来将流(键控或非键控)与非广播流(以键BroadcastStream为参数)进行连接。我们可以调用特殊类型CoProcessFunction的process()方法,这将返回一个BroadcastConnectedStream。该函数将包含我们的匹配逻辑。函数的确切类型取决于非广播流的类型:
- 如果输入了密码,则该函数为KeyedBroadcastProcessFunction。
- 如果它是非键,则该函数为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