简介: 介绍如何在 Python DataStream API 中使用 state & timer 功能。

一、背景

Flink 1.13 已于近期正式发布,超过 200 名贡献者参与了 Flink 1.13 的开发,提交了超过 1000 个 commits,完成了若干重要功能。其中,PyFlink 模块在该版本中也新增了若干重要功能,比如支持了 state、自定义 window、row-based operation 等。随着这些功能的引入,PyFlink 功能已经日趋完善,用户可以使用 Python 语言完成绝大多数类型Flink作业的开发。接下来,我们详细介绍如何在 Python DataStream API 中使用 state & timer 功能。

二、state 功能介绍

作为流计算引擎,state 是 Flink 中最核心的功能之一。

  • 在 1.12 中,Python DataStream API 尚不支持 state,用户使用 Python DataStream API 只能实现一些简单的、不需要使用 state 的应用;
  • 而在 1.13 中,Python DataStream API 支持了此项重要功能。

state 使用示例

如下是一个简单的示例,说明如何在 Python DataStream API 作业中使用 state:

from pyflink.common import WatermarkStrategy, Row
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors import NumberSequenceSource
from pyflink.datastream.functions import RuntimeContext, MapFunction
from pyflink.datastream.state import ValueStateDescriptor class MyMapFunction(MapFunction): def open(self, runtime_context: RuntimeContext):
state_desc = ValueStateDescriptor('cnt', Types.LONG())
# 定义value state
self.cnt_state = runtime_context.get_state(state_desc) def map(self, value):
cnt = self.cnt_state.value()
if cnt is None:
cnt = 0 new_cnt = cnt + 1
self.cnt_state.update(new_cnt)
return value[0], new_cnt def state_access_demo():
# 1. 创建 StreamExecutionEnvironment
env = StreamExecutionEnvironment.get_execution_environment() # 2. 创建数据源
seq_num_source = NumberSequenceSource(1, 100)
ds = env.from_source(
source=seq_num_source,
watermark_strategy=WatermarkStrategy.for_monotonous_timestamps(),
source_name='seq_num_source',
type_info=Types.LONG()) # 3. 定义执行逻辑
ds = ds.map(lambda a: Row(a % 4, 1), output_type=Types.ROW([Types.LONG(), Types.LONG()])) \
.key_by(lambda a: a[0]) \
.map(MyMapFunction(), output_type=Types.TUPLE([Types.LONG(), Types.LONG()])) # 4. 将打印结果数据
ds.print() # 5. 执行作业
env.execute() if __name__ == '__main__':
state_access_demo()

在上面的例子中,我们定义了一个 MapFunction,该 MapFunction 中定义了一个名字为 “cnt_state” 的 ValueState,用于记录每一个 key 出现的次数。

说明:

  • 除了 ValueState 之外,Python DataStream API 还支持 ListState、MapState、ReducingState,以及 AggregatingState;
  • 定义 state 的 StateDescriptor 时,需要声明 state 中所存储的数据的类型(TypeInformation)。另外需要注意的是,当前 TypeInformation 字段并未被使用,默认使用 pickle 进行序列化,因此建议将 TypeInformation 字段定义为 Types.PICKLED_BYTE_ARRAY() 类型,与实际所使用的序列化器相匹配。这样的话,当后续版本支持使用 TypeInformation 之后,可以保持后向兼容性;
  • state 除了可以在 KeyedStream 的 map 操作中使用,还可以在其它操作中使用;除此之外,还可以在连接流中使用 state,比如:
ds1 = ...  # type DataStream
ds2 = ... # type DataStream
ds1.connect(ds2) \
.key_by(key_selector1=lambda a: a[0], key_selector2=lambda a: a[0]) \
.map(MyCoMapFunction()) # 可以在MyCoMapFunction中使用state

可以使用 state 的 API 列表如下:

  操作 自定义函数
KeyedStream map MapFunction
flat_map FlatMapFunction  
reduce ReduceFunction  
filter FilterFunction  
process KeyedProcessFunction  
ConnectedStreams map CoMapFunction
flat_map CoFlatMapFunction  
process KeyedCoProcessFunction  
WindowedStream apply WindowFunction
  process ProcessWindowFunction

state 工作原理

上图是 PyFlink 中,state 工作原理的架构图。从图中我们可以看出,Python 自定义函数运行在 Python worker 进程中,而 state backend 运行在 JVM 进程中(由 Java 算子来管理)。当 Python 自定义函数需要访问 state 时,会通过远程调用的方式,访问 state backend。

我们知道,远程调用的开销是非常大的,为了提升 state 读写的性能,PyFlink 针对 state 读写做了以下几个方面的优化工作:

  • Lazy Read:

    对于包含多个 entry 的 state,比如 MapState,当遍历 state 时,state 数据并不会一次性全部读取到 Python worker 中,只有当真正需要访问时,才从 state backend 读取。

  • Async Write:

    当更新 state 时,更新后的 state,会先存储在 LRU cache 中,并不会同步地更新到远端的 state backend,这样做可以避免每次 state 更新操作都访问远端的 state backend;同时,针对同一个 key 的多次更新操作,可以合并执行,尽量避免无效的 state 更新。

  • LRU cache:

    在 Python worker 进程中维护了 state 读写的 cache。当读取某个 key 时,会先查看其是否已经被加载到读 cache 中;当更新某个 key 时,会先将其存放到写 cache 中。针对频繁读写的 key,LRU cache 可以避免每次读写操作,都访问远端的 state backend,对于有热点 key 的场景,可以极大提升 state 读写性能。

  • Flush on Checkpoint:

    为了保证 checkpoint 语义的正确性,当 Java 算子需要执行 checkpoint时,会将 Python worker中的写 cache 都 flush 回 state backend。

其中 LRU cache 可以细分为二级,如下图所示:

说明:

  • 二级 cache 为 global cache,二级 cache 中的读 cache 中存储着当前 Python worker 进程中所有缓存的原始 state 数据(未反序列化);二级 cache 中的写 cache 中存储着当前 Python worker 进程中所有创建的 state 对象。
  • 一级 cache 位于每一个 state 对象内,在 state 对象中缓存着该 state 对象已经从远端的 state backend 读取的 state 数据以及待更新回远端的 state backend 的 state 数据。

工作流程:

  • 当在 Python UDF 中,创建一个 state 对象时,首先会查看当前 key 所对应的 state 对象是否已经存在(在二级 cache 中的 “Global Write Cache” 中查找),如果存在,则返回对应的 state 对象;如果不存在,则创建新的 state 对象,并存入 “Global Write Cache”;
  • state 读取:当在 Python UDF 中,读取 state 对象时,如果待读取的 state 数据已经存在(一级 cache),比如对于 MapState,待读取的 map key/map value 已经存在,则直接返回对应的 map key/map value;否则,访问二级 cache,如果二级 cache 中也不存在待读取的 state 数据,则从远端的 state backend 读取;
  • state 写入:当在 Python UDF 中,更新 state 对象时,先写到 state 对象内部的写 cache 中(一级 cache);当 state 对象中待写回 state backend 的 state 数据的大小超过指定阈值或者当遇到 checkpoint 时,将待写回的 state 数据写回远端的 state backend。

state 性能调优

通过前一节的介绍,我们知道 PyFlink 使用了多种优化手段,用于提升 state 读写的性能,这些优化行为可以通过以下参数配置:

配置 说明
python.state.cache-size Python worker 中读 cache 以及写 cache 的大小。(二级 cache)需要注意的是:读 cache、写 cache是独立的,当前不支持分别配置读 cache 以及写 cache 的大小。
python.map-state.iterate-response-batch-size 当遍历 MapState 时,每次从 state backend 读取并返回给 Python worker 的 entry 的最大个数。
python.map-state.read-cache-size 一个 MapState 的读 cache 中最大允许的 entry 个数(一级 cache)。当一个 MapState 中,读 cache 中的 entry 个数超过该阈值时,会通过 LRU 策略从读 cache 中删除最近最少访问过的 entry。
python.map-state.write-cache-size 一个 MapState 的写 cache 中最大允许的待更新 entry 的个数(一级 cache)。当一个 MapState 中,写 cache 中待更新的 entry 的个数超过该阈值时,会将该 MapState 下所有待更新 state 数据写回远端的 state backend。

需要注意的是,state 读写的性能不仅取决于以上参数,还受其它因素的影响,比如:

  • 输入数据中 key 的分布:

    输入数据的 key 越分散,读 cache 命中的概率越低,则性能越差。

  • Python UDF 中 state 读写次数:

    state 读写可能涉及到读写远端的 state backend,应该尽量优化 Python UDF 的实现,减少不必要的 state 读写。

  • checkpoint interval:

    为了保证 checkpoint 语义的正确性,当遇到 checkpoint 时,Python worker 会将所有缓存的待更新 state 数据,写回 state backend。如果配置的 checkpoint interval 过小,则可能并不能有效减少 Python worker 写回 state backend 的数据量。

  • bundle size / bundle time:

    当前 Python 算子会将输入数据划分成多个批次,发送给 Python worker 执行。当一个批次的数据处理完之后,会强制将 Python worker 进程中的待更新 state 写回 state backend。与 checkpoint interval 类似,该行为也可能会影响 state 写性能。批次的大小可以通过 python.fn-execution.bundle.size 和 python.fn-execution.bundle.time 参数控制。

三、timer 功能介绍

timer 使用示例

除了 state 之外,用户还可以在 Python DataStream API 中使用定时器 timer。

import datetime

from pyflink.common import Row, WatermarkStrategy
from pyflink.common.typeinfo import Types
from pyflink.common.watermark_strategy import TimestampAssigner
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.functions import KeyedProcessFunction, RuntimeContext
from pyflink.datastream.state import ValueStateDescriptor
from pyflink.table import StreamTableEnvironment class CountWithTimeoutFunction(KeyedProcessFunction): def __init__(self):
self.state = None def open(self, runtime_context: RuntimeContext):
self.state = runtime_context.get_state(ValueStateDescriptor(
"my_state", Types.ROW([Types.STRING(), Types.LONG(), Types.LONG()]))) def process_element(self, value, ctx: 'KeyedProcessFunction.Context'):
# retrieve the current count
current = self.state.value()
if current is None:
current = Row(value.f1, 0, 0) # update the state's count
current[1] += 1 # set the state's timestamp to the record's assigned event time timestamp
current[2] = ctx.timestamp() # write the state back
self.state.update(current) # schedule the next timer 60 seconds from the current event time
ctx.timer_service().register_event_time_timer(current[2] + 60000) def on_timer(self, timestamp: int, ctx: 'KeyedProcessFunction.OnTimerContext'):
# get the state for the key that scheduled the timer
result = self.state.value() # check if this is an outdated timer or the latest timer
if timestamp == result[2] + 60000:
# emit the state on timeout
yield result[0], result[1] class MyTimestampAssigner(TimestampAssigner): def __init__(self):
self.epoch = datetime.datetime.utcfromtimestamp(0) def extract_timestamp(self, value, record_timestamp) -> int:
return int((value[0] - self.epoch).total_seconds() * 1000) if __name__ == '__main__':
env = StreamExecutionEnvironment.get_execution_environment()
t_env = StreamTableEnvironment.create(stream_execution_environment=env) t_env.execute_sql("""
CREATE TABLE my_source (
a TIMESTAMP(3),
b VARCHAR,
c VARCHAR
) WITH (
'connector' = 'datagen',
'rows-per-second' = '10'
)
""") stream = t_env.to_append_stream(
t_env.from_path('my_source'),
Types.ROW([Types.SQL_TIMESTAMP(), Types.STRING(), Types.STRING()]))
watermarked_stream = stream.assign_timestamps_and_watermarks(
WatermarkStrategy.for_monotonous_timestamps()
.with_timestamp_assigner(MyTimestampAssigner())) # apply the process function onto a keyed stream
watermarked_stream.key_by(lambda value: value[1])\
.process(CountWithTimeoutFunction()) \
.print() env.execute()

在上述示例中,我们定义了一个 KeyedProcessFunction,该 KeyedProcessFunction 记录每一个 key 出现的次数,当一个 key 超过 60 秒没有更新时,会将该 key 以及其出现次数,发送到下游节点。

除了 event time timer 之外,用户还可以使用 processing time timer。

timer 工作原理

timer 的工作流程是这样的:

  • 与 state 访问使用单独的通信信道不同,当用户注册 timer 之后,注册消息通过数据通道发送到 Java 算子;
  • Java 算子收到 timer 注册消息之后,首先检查待注册 timer 的触发时间,如果已经超过当前时间,则直接触发;否则的话,将 timer 注册到 Java 算子的 timer service 中;
  • 当 timer 触发之后,触发消息通过数据通道发送到 Python worker,Python worker 回调用户 Python UDF 中的的 on_timer 方法。

需要注意的是:由于 timer 注册消息以及触发消息通过数据通道异步地在 Java 算子以及 Python worker 之间传输,这会造成在某些场景下,timer 的触发可能没有那么及时。比如当用户注册了一个 processing time timer,当 timer 触发之后,触发消息通过数据通道传输到 Python UDF 时,可能已经是几秒中之后了。

四、总结

在这篇文章中,我们主要介绍了如何在 Python DataStream API 作业中使用 state & timer,state & timer 的工作原理以及如何进行性能调优。接下来,我们会继续推出 PyFlink 系列文章,帮助 PyFlink 用户深入了解 PyFlink 中各种功能、应用场景以及最佳实践等。

原文链接
本文为阿里云原创内容,未经允许不得转载。

PyFlink 教程(三):PyFlink DataStream API - state & timer的更多相关文章

  1. Flink Program Guide (8) -- Working with State :Fault Tolerance(DataStream API编程指导 -- For Java)

    Working with State 本文翻译自Streaming Guide/ Fault Tolerance / Working with State ---------------------- ...

  2. Flink-v1.12官方网站翻译-P002-Fraud Detection with the DataStream API

    使用DataStream API进行欺诈检测 Apache Flink提供了一个DataStream API,用于构建强大的.有状态的流式应用.它提供了对状态和时间的精细控制,这使得高级事件驱动系统的 ...

  3. Flink Program Guide (10) -- Savepoints (DataStream API编程指导 -- For Java)

    Savepoint 本文翻译自文档Streaming Guide / Savepoints ------------------------------------------------------ ...

  4. Flink Program Guide (2) -- 综述 (DataStream API编程指导 -- For Java)

    v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VM ...

  5. flink DataStream API使用及原理

    传统的大数据处理方式一般是批处理式的,也就是说,今天所收集的数据,我们明天再把今天收集到的数据算出来,以供大家使用,但是在很多情况下,数据的时效性对于业务的成败是非常关键的. Spark 和 Flin ...

  6. abp学习(四)——根据入门教程(aspnetMVC Web API进一步学习)

    Introduction With AspNet MVC Web API EntityFramework and AngularJS 地址:https://aspnetboilerplate.com/ ...

  7. Elasticsearch入门教程(三):Elasticsearch索引&映射

    原文:Elasticsearch入门教程(三):Elasticsearch索引&映射 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文 ...

  8. Flink DataStream API 中的多面手——Process Function详解

    之前熟悉的流处理API中的转换算子是无法访问事件的时间戳信息和水位线信息的.例如:MapFunction 这样的map转换算子就无法访问时间戳或者当前事件的时间. 然而,在一些场景下,又需要访问这些信 ...

  9. Flink Application Development DataStream API Operators Overview-- Flink应用程序开发DataStream API操作符概览

    目录 概览 DataStream转换 物理分区 任务链和资源组 翻译原文- Application Development DataStream API Operators 概览 操作符将一个或多个D ...

  10. Flink DataStream API Programming Guide

    Example Program The following program is a complete, working example of streaming window word count ...

随机推荐

  1. C 可变参数函数分析(va_start,va_end,va_list...)

    PS:要转载请注明出处,本人版权所有. PS: 这个只是基于<我自己>的理解, 如果和你的原则及想法相冲突,请谅解,勿喷. 前置说明   本文作为本人csdn blog的主站的备份.(Bl ...

  2. 2、Azure Devops之Azure Boards使用

    1.什么是Azure Boards 使用面板.积压工作.冲刺.查询管理项目的用户故事.待办事项.任务.特性和bug. 2.工作项(WorkItem) 工作项管理的可以管理和创建用户故事.特性.任务. ...

  3. Mysql范式

    什么是范式? "范式(NF)"是"符合某一种级别的关系模式的集合,表示一个关系内部各属性之间的联系的合理化程度".很晦涩吧?实际上你可以把它粗略地理解为一张数据 ...

  4. Django:Could not find backend 'django_redis.cache.RedisCache': cannot import name 'six'

    1.报错内容: django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'django_red ...

  5. Csharp学习Linq

    Linq的学习 这里继续使用之前文章创建的学生类,首先简单介绍一下linq的使用. Student.cs public class Student { public int Id { get; set ...

  6. 三维模型3DTILE格式轻量化压缩主要技术方法浅析

    三维模型3DTILE格式轻量化压缩主要技术方法浅析 三维模型3DTILE格式轻量化压缩主要技术方法浅析 随着三维地理空间数据的应用日益广泛,为了更快速地传输和存储这些大规模数据,3DTile格式的轻量 ...

  7. 三维模型3DTile格式轻量化压缩处理效率提高的技术方浅析

    三维模型3DTile格式轻量化压缩处理效率提高的技术方浅析 随着三维模型在各个领域的广泛应用,对于其格式的轻量化压缩处理和效率提高的需求也越发迫切.本文将介绍一些技术方法,帮助实现三维模型3DTile ...

  8. Orleans - 1 .NET生态构建分布式系统的利器

    在当今数字化时代,构建高效.可靠的分布式系统是许多企业和开发团队面临的挑战.微软的 Orleans 框架为解决这些挑战提供了一个强大而简单的解决方案.本文将介绍 Orleans 的核心概念,并通过一个 ...

  9. 《.NET内存管理宝典》 售后服务系列文(2) - WinDbg命令.cmdtree

    此文是<.NET内存管理宝典   提高代码质量.性能和可扩展性>(英文名<Pro .NET Memory Management: For Better Code, Performan ...

  10. quartus之rom的IP测试

    quartus之rom的IP测试 1.rom的作用 rom,就是只读存储器,内部数据在下载电路时就已经确认,不能使用信号驱动更改,只能够读取,一般用于比较重要的配置数据.在quartus中,可以直接调 ...