在Apache beam中,固定窗口是由特定的开始时间和时间间隔定义的。固定窗口的开始时间是由窗口的时钟实例确定的,根据窗口的时间间隔进行对齐。例如,如果我们想要从Epoch开始每隔1小时创建一个固定的窗口,可以使用以下代码示例:
import apache_beam as beam
from apache_beam.transforms.window import FixedWindows
from apache_beam.io.gcp.pubsub import ReadFromPubSub
def run():
with beam.Pipeline() as p:
windowed_messages = (p
| 'ReadFromPubSub' >> ReadFromPubSub(subscription=subscription)
| 'WindowInto' >> beam.WindowInto(FixedWindows(3600))
| 'ProcessData' >> beam.ParDo(DoSomething()))
if __name__ == '__main__':
run()
在上述代码中,我们从Pub/Sub中读取消息并使用FixedWindows函数将它们划分为1小时的固定窗口。然后,我们可以使用DOsomething函数处理每个窗口中的消息。