PyFlink 教程(三):PyFlink DataStream API - state & timer
简介: 介绍如何在 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的更多相关文章
- Flink Program Guide (8) -- Working with State :Fault Tolerance(DataStream API编程指导 -- For Java)
Working with State 本文翻译自Streaming Guide/ Fault Tolerance / Working with State ---------------------- ...
- Flink-v1.12官方网站翻译-P002-Fraud Detection with the DataStream API
使用DataStream API进行欺诈检测 Apache Flink提供了一个DataStream API,用于构建强大的.有状态的流式应用.它提供了对状态和时间的精细控制,这使得高级事件驱动系统的 ...
- Flink Program Guide (10) -- Savepoints (DataStream API编程指导 -- For Java)
Savepoint 本文翻译自文档Streaming Guide / Savepoints ------------------------------------------------------ ...
- Flink Program Guide (2) -- 综述 (DataStream API编程指导 -- For Java)
v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VM ...
- flink DataStream API使用及原理
传统的大数据处理方式一般是批处理式的,也就是说,今天所收集的数据,我们明天再把今天收集到的数据算出来,以供大家使用,但是在很多情况下,数据的时效性对于业务的成败是非常关键的. Spark 和 Flin ...
- abp学习(四)——根据入门教程(aspnetMVC Web API进一步学习)
Introduction With AspNet MVC Web API EntityFramework and AngularJS 地址:https://aspnetboilerplate.com/ ...
- Elasticsearch入门教程(三):Elasticsearch索引&映射
原文:Elasticsearch入门教程(三):Elasticsearch索引&映射 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文 ...
- Flink DataStream API 中的多面手——Process Function详解
之前熟悉的流处理API中的转换算子是无法访问事件的时间戳信息和水位线信息的.例如:MapFunction 这样的map转换算子就无法访问时间戳或者当前事件的时间. 然而,在一些场景下,又需要访问这些信 ...
- Flink Application Development DataStream API Operators Overview-- Flink应用程序开发DataStream API操作符概览
目录 概览 DataStream转换 物理分区 任务链和资源组 翻译原文- Application Development DataStream API Operators 概览 操作符将一个或多个D ...
- Flink DataStream API Programming Guide
Example Program The following program is a complete, working example of streaming window word count ...
随机推荐
- C# PaddleOCR 车牌识别
效果 车牌识别测试地址 http://47.108.88.211/manual/VehPlateTest.html 通用OCR识别测试地址 http://47.108.88.211/manual/OC ...
- Java jdbcTemplate 获取数据表结构
表结构如图 代码 @Autowired JdbcTemplate jdbcTemplate; @Test public void getColumnNames() throws Exception { ...
- mysql---插入日期类型的数据并把其设置为主键
Python日期格式化方法 import datetime datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") dt=dat ...
- Echarts入门案例教程
一.定义容器变量并获取页面div元素 1 var chartDom = document.getElementById('chart3'); 二.初始化容器 1 var myChart = echar ...
- 2024年:如何根据项目具体情况选择合适的CSS技术栈
2024年:如何根据项目具体情况选择合适的CSS技术栈 (请注意,这是一篇主观且充满个人技术偏好的文章) 方案一: antd/element ui/类似竞品 适合情形: 项目没有设计师 or 大部分人 ...
- #扩展域并查集,线段树分治#CF576E Painting Edges
题目链接 题目翻译 给定一张 \(n\) 个点 \(m\) 条边的无向图. 一共有 \(k\) 种颜色,一开始,每条边都没有颜色. 定义合法状态为仅保留染成 \(k\) 种颜色中的任何一种颜色的边,图 ...
- 响应式系统reactive system初探
目录 初识响应式系统 什么是响应式系统 响应式系统的四大特点 及时响应性(Responsive) 恢复性(Resilient) 有弹性(Elastic) 消息驱动(Message Driven) 总结 ...
- RabbitMQ 07 发布订阅模式
发布订阅模式 发布订阅模式结构图: 比如信用卡还款日临近了,那么就会给手机.邮箱发送消息,提示需要去还款了,但是手机短信和邮件发送并不一定是同一个业务提供的,但是现在又希望能够都去执行,就可以用到发布 ...
- MogDB/openGauss 坏块测试-对启动的影响-测试笔记1
MogDB/openGauss 坏块测试-对启动的影响-测试笔记 1 在 UPDATE 操作提交后,脏块落盘前 kill 掉 mogdb 数据库,然后对 UPDATE 修改的坏进行以下破坏操作,仍然能 ...
- Mybatis实现增删改查
1.CRUD 1.1namespace namespace中的包名必须和Dao/mapper接口包名一致 1.2select 选择,查询语句 id:就是对应的namespace中的方法名 resul ...