Flink实战(七十五):flink-sql使用(三)简介(三)配置

时间:2024-10-30 06:57:52

1 配置

SQL 客户端启动时可以添加 CLI 选项,具体如下。

复制代码

  1. ./bin/ embedded --help
  2. Mode "embedded" submits Flink jobs from the local machine.
  3. Syntax: embedded [OPTIONS]
  4. "embedded" mode options:
  5. -d,--defaults <environment file> The environment properties with which
  6. every new session is initialized.
  7. Properties might be overwritten by
  8. session properties.
  9. -e,--environment <environment file> The environment properties to be
  10. imported into the session. It might
  11. overwrite default environment
  12. properties.
  13. -h,--help Show the help message with
  14. descriptions of all options.
  15. -hist,--history <History file path> The file which you want to save the
  16. command history into. If not
  17. specified, we will auto-generate one
  18. under your user's home directory.
  19. -j,--jar <JAR file> A JAR file to be imported into the
  20. session. The file might contain
  21. user-defined classes needed for the
  22. execution of statements such as
  23. functions, table sources, or sinks.
  24. Can be used multiple times.
  25. -l,--library <JAR directory> A JAR file directory with which every
  26. new session is initialized. The files
  27. might contain user-defined classes
  28. needed for the execution of
  29. statements such as functions, table
  30. sources, or sinks. Can be used
  31. multiple times.
  32. -pyarch,--pyArchives <arg> Add python archive files for job. The
  33. archive files will be extracted to
  34. the working directory of python UDF
  35. worker. Currently only zip-format is
  36. supported. For each archive file, a
  37. target directory be specified. If the
  38. target directory name is specified,
  39. the archive file will be extracted to
  40. a name can directory with the
  41. specified name. Otherwise, the
  42. archive file will be extracted to a
  43. directory with the same name of the
  44. archive file. The files uploaded via
  45. this option are accessible via
  46. relative path. '#' could be used as
  47. the separator of the archive file
  48. path and the target directory name.
  49. Comma (',') could be used as the
  50. separator to specify multiple archive
  51. files. This option can be used to
  52. upload the virtual environment, the
  53. data files used in Python UDF (.:
  54. --pyArchives
  55. file:///tmp/py37.zip,file:///tmp/data
  56. .zip#data --pyExecutable
  57. py37.zip/py37/bin/python). The data
  58. files could be accessed in Python
  59. UDF, .: f = open('data/',
  60. 'r').
  61. -pyexec,--pyExecutable <arg> Specify the path of the python
  62. interpreter used to execute the
  63. python UDF worker (.:
  64. --pyExecutable
  65. /usr/local/bin/python3). The python
  66. UDF worker depends on Python 3.5+,
  67. Apache Beam (version == 2.19.0), Pip
  68. (version >= 7.1.0) and SetupTools
  69. (version >= 37.0.0). Please ensure
  70. that the specified environment meets
  71. the above requirements.
  72. -pyfs,--pyFiles <pythonFiles> Attach custom python files for job.
  73. These files will be added to the
  74. PYTHONPATH of both the local client
  75. and the remote python UDF worker. The
  76. standard python resource file
  77. suffixes such as .py/.egg/.zip or
  78. directory are all supported. Comma
  79. (',') could be used as the separator
  80. to specify multiple files (.:
  81. --pyFiles
  82. file:///tmp/myresource.zip,hdfs:///$n
  83. amenode_address/myresource2.zip).
  84. -pyreq,--pyRequirements <arg> Specify a file which
  85. defines the third-party dependencies.
  86. These dependencies will be installed
  87. and added to the PYTHONPATH of the
  88. python UDF worker. A directory which
  89. contains the installation packages of
  90. these dependencies could be specified
  91. optionally. Use '#' as the separator
  92. if the optional parameter exists
  93. (.: --pyRequirements
  94. file:///tmp/#file:///
  95. tmp/cached_dir).
  96. -s,--session <session identifier> The identifier for a session.
  97. 'default' is the default identifier.
  98. -u,--update <SQL update statement> Experimental (for testing only!):
  99. Instructs the SQL Client to
  100. immediately execute the given update
  101. statement after starting up. The
  102. process is shut down after the
  103. statement has been submitted to the
  104. cluster and returns an appropriate
  105. return code. Currently, this feature
  106. is only supported for INSERT INTO
  107. statements that declare the target
  108. sink table.

复制代码

1.1 环境配置文件

SQL 查询执行前需要配置相关环境变量。环境配置文件 定义了 catalog、table sources、table sinks、用户自定义函数和其他执行或部署所需属性。

每个环境配置文件是常规的 YAML 文件,例子如下。

复制代码

  1. # 定义表,如 source、sink、视图或临时表。
  2. tables:
  3. - name: MyTableSource
  4. type: source-table
  5. update-mode: append
  6. connector:
  7. type: filesystem
  8. path: "/path/to/"
  9. format:
  10. type: csv
  11. fields:
  12. - name: MyField1
  13. data-type: INT
  14. - name: MyField2
  15. data-type: VARCHAR
  16. line-delimiter: "\n"
  17. comment-prefix: "#"
  18. schema:
  19. - name: MyField1
  20. data-type: INT
  21. - name: MyField2
  22. data-type: VARCHAR
  23. - name: MyCustomView
  24. type: view
  25. query: "SELECT MyField2 FROM MyTableSource"
  26. # 定义用户自定义函数
  27. functions:
  28. - name: myUDF
  29. from: class
  30. class:
  31. constructor:
  32. - 7.6
  33. - false
  34. # 定义 catalogs
  35. catalogs:
  36. - name: catalog_1
  37. type: hive
  38. property-version: 1
  39. hive-conf-dir: ...
  40. - name: catalog_2
  41. type: hive
  42. property-version: 1
  43. default-database: mydb2
  44. hive-conf-dir: ...
  45. # 改变表程序基本的执行行为属性。
  46. execution:
  47. planner: blink # 可选: 'blink' (默认)或 'old'
  48. type: streaming # 必选:执行模式为 'batch''streaming'
  49. result-mode: table # 必选:'table''changelog'
  50. max-table-result-rows: 1000000 # 可选:'table' 模式下可维护的最大行数(默认为 1000000,小于 1 则表示无限制)
  51. time-characteristic: event-time # 可选: 'processing-time''event-time' (默认)
  52. parallelism: 1 # 可选:Flink 的并行数量(默认为 1
  53. periodic-watermarks-interval: 200 # 可选:周期性 watermarks 的间隔时间(默认 200 ms)
  54. max-parallelism: 16 # 可选:Flink 的最大并行数量(默认 128
  55. min-idle-state-retention: 0 # 可选:表程序的最小空闲状态时间
  56. max-idle-state-retention: 0 # 可选:表程序的最大空闲状态时间
  57. current-catalog: catalog_1 # 可选:当前会话 catalog 的名称(默认为 'default_catalog'
  58. current-database: mydb1 # 可选:当前 catalog 的当前数据库名称
  59. # (默认为当前 catalog 的默认数据库)
  60. restart-strategy: # 可选:重启策略(restart-strategy)
  61. type: fallback # 默认情况下“回退”到全局重启策略
  62. # 用于调整和调优表程序的配置选项。
  63. # 在专用的”配置”页面上可以找到完整的选项列表及其默认值。
  64. configuration:
  65. table.-reorder-enabled: true
  66. table.: true
  67. table.-size: 128kb
  68. # 描述表程序提交集群的属性。
  69. deployment:
  70. response-timeout: 5000

复制代码

上述配置:

  • 定义一个从 CSV 文件中读取的 table source MyTableSource 所需的环境,
  • 定义了一个视图 MyCustomView ,该视图是用 SQL 查询声明的虚拟表,
  • 定义了一个用户自定义函数 myUDF,该函数可以使用类名和两个构造函数参数进行实例化,
  • 连接到两个 Hive catalogs 并用 catalog_1 来作为当前目录,用 mydb1 来作为该目录的当前数据库,
  • streaming 模式下用 blink planner 来运行时间特征为 event-time 和并行度为 1 的语句,
  • 在 table 结果模式下运行试探性的(exploratory)的查询,
  • 并通过配置选项对联结(join)重排序和溢出进行一些计划调整。

根据使用情况,配置可以被拆分为多个文件。因此,一般情况下(用 --defaults 指定默认环境配置文件)以及基于每个会话(用 --environment 指定会话环境配置文件)来创建环境配置文件。每个 CLI 会话均会被属于 session 属性的默认属性初始化。例如,默认环境配置文件可以指定在每个会话中都可用于查询的所有 table source,而会话环境配置文件仅声明特定的状态保留时间和并行性。启动 CLI 应用程序时,默认环境配置文件和会话环境配置文件都可以被指定。如果未指定默认环境配置文件,则 SQL 客户端将在 Flink 的配置目录中搜索 ./conf/

注意 在 CLI 会话中设置的属性(如 SET 命令)优先级最高:

CLI commands > session environment file > defaults environment file

重启策略(Restart Strategies)

重启策略控制 Flink 作业失败时的重启方式。与 Flink 集群的全局重启策略相似,更细精度的重启配置可以在环境配置文件中声明。

Flink 支持以下策略:

复制代码

  1. execution:
  2. # 退回到 中定义的全局策略
  3. restart-strategy:
  4. type: fallback
  5. # 作业直接失败并且不尝试重启
  6. restart-strategy:
  7. type: none
  8. # 最多重启作业的给定次数
  9. restart-strategy:
  10. type: fixed-delay
  11. attempts: 3 # 作业被宣告失败前的重试次数(默认:Integer.MAX_VALUE)
  12. delay: 10000 # 重试之间的间隔时间,以毫秒为单位(默认:10 秒)
  13. # 只要不超过每个时间间隔的最大故障数就继续尝试
  14. restart-strategy:
  15. type: failure-rate
  16. max-failures-per-interval: 1 # 每个间隔重试的最大次数(默认:1)
  17. failure-rate-interval: 60000 # 监测失败率的间隔时间,以毫秒为单位
  18. delay: 10000 # 重试之间的间隔时间,以毫秒为单位(默认:10 秒)

复制代码

1.2 依赖

SQL 客户端不要求用 Maven 或者 SBT 设置 Java 项目。相反,你可以以常规的 JAR 包给集群提交依赖项。你也可以分别(用 --jar)指定每一个 JAR 包或者(用 --library)定义整个 library 依赖库。为连接扩展系统(如 Apache Kafka)和相应的数据格式(如 JSON),Flink提供了开箱即用型 JAR 捆绑包(ready-to-use JAR bundles)。这些 JAR 包各个发行版都可以从 Maven *库中下载到。

提供的 SQL JARs 和使用文档的完整清单可以在连接扩展系统页面中找到。

如下例子展示了从 Apache Kafka 中读取 JSON 文件并作为 table source 的环境配置文件。

复制代码

  1. tables:
  2. - name: TaxiRides
  3. type: source-table
  4. update-mode: append
  5. connector:
  6. property-version: 1
  7. type: kafka
  8. version: "0.11"
  9. topic: TaxiRides
  10. startup-mode: earliest-offset
  11. properties:
  12. : localhost:9092
  13. : testGroup
  14. format:
  15. property-version: 1
  16. type: json
  17. schema: "ROW<rideId LONG, lon FLOAT, lat FLOAT, rideTime TIMESTAMP>"
  18. schema:
  19. - name: rideId
  20. data-type: BIGINT
  21. - name: lon
  22. data-type: FLOAT
  23. - name: lat
  24. data-type: FLOAT
  25. - name: rowTime
  26. data-type: TIMESTAMP(3)
  27. rowtime:
  28. timestamps:
  29. type: "from-field"
  30. from: "rideTime"
  31. watermarks:
  32. type: "periodic-bounded"
  33. delay: "60000"
  34. - name: procTime
  35. data-type: TIMESTAMP(3)
  36. proctime: true

复制代码

TaxiRide 表的结果格式与绝大多数的 JSON 格式相似。此外,它还添加了 rowtime 属性 rowTime 和 processing-time 属性 procTime

connector 和 format 都允许定义属性版本(当前版本为 1 )以便将来向后兼容。

1.3 自定义函数(User-defined Functions)

SQL 客户端允许用户创建用户自定义的函数来进行 SQL 查询。当前,这些自定义函数仅限于 Java/Scala 编写的类以及 Python 文件。

为提供 Java/Scala 的自定义函数,你首先需要实现和编译函数类,该函数继承自 ScalarFunction、 AggregateFunction 或 TableFunction(见自定义函数)。一个或多个函数可以打包到 SQL 客户端的 JAR 依赖中。

为提供 Python 的自定义函数,你需要编写 Python 函数并且用装饰器  或  来装饰(见 Python UDFs))。Python 文件中可以放置一个或多个函数。其Python 文件和相关依赖需要通过在环境配置文件中或命令行选项(见 命令行用法)配置中特别指定(见 Python 配置)。

所有函数在被调用之前,必须在环境配置文件中提前声明。functions 列表中每个函数类都必须指定

  • 用来注册函数的 name
  • 函数的来源 from(目前仅限于 class(Java/Scala UDF)或 python(Python UDF)),

Java/Scala UDF 必须指定:

  • 声明了全限定名的函数类 class 以及用于实例化的 constructor 参数的可选列表。

Python UDF 必须指定:

  • 声明全程名称的 fully-qualified-name,即函数的 “[module name].[object name]”

复制代码

  1. functions:
  2. - name: java_udf # required: name of the function
  3. from: class # required: source of the function
  4. class: ... # required: fully qualified class name of the function
  5. constructor: # optional: constructor parameters of the function class
  6. - ... # optional: a literal parameter with implicit type
  7. - class: ... # optional: full class name of the parameter
  8. constructor: # optional: constructor parameters of the parameter's class
  9. - type: ... # optional: type of the literal parameter
  10. value: ... # optional: value of the literal parameter
  11. - name: python_udf # required: name of the function
  12. from: python # required: source of the function
  13. fully-qualified-name: ... # required: fully qualified class name of the function

复制代码

对于 Java/Scala UDF,要确保函数类指定的构造参数顺序和类型都要严格匹配。

构造函数参数

根据用户自定义函数可知,在用到 SQL 语句中之前,有必要将构造参数匹配对应的类型。

如上述示例所示,当声明一个用户自定义函数时,可以使用构造参数来配置相应的类,有以下三种方式:

隐式类型的文本值:SQL 客户端将自动根据文本推导对应的类型。目前,只支持 BOOLEANINT、 DOUBLE 和 VARCHAR 。

如果自动推导的类型与期望不符(例如,你需要 VARCHAR 类型的 false),可以改用显式类型。

  1. - true # -> BOOLEAN (case sensitive)
  2. - 42 # -> INT
  3. - 1234.222 # -> DOUBLE
  4. - foo # -> VARCHAR

显式类型的文本值:为保证类型安全,需明确声明 type 和 value 属性的参数。

  1. - type: DECIMAL
  2. value: 11111111111111111

下表列出支持的 Java 参数类型和与之相对应的 SQL 类型。

Java 类型 SQL 类型
DECIMAL
BOOLEAN
TINYINT
DOUBLE
REALFLOAT
INTEGERINT
BIGINT
SMALLINT
VARCHAR

其他类型 (例如 TIMESTAMP 和 ARRAY)、原始类型和 null 目前还不支持。

(嵌套)类实例:除了文本值外,还可以通过指定构造参数的 class 和 constructor 属性来创建(嵌套)类实例。这个过程可以递归执行,直到最后的构造参数是用文本值来描述的。

复制代码

  1. - class:
  2. constructor:
  3. - StarryName
  4. - class:
  5. constructor:
  6. - class: .String
  7. constructor:
  8. - type: VARCHAR
  9. value: 3

 2 扩展

  1. ==============================================================================
  2. **Table Sources**
  3. ==============================================================================
  4. Define table sources here. See the Table API & SQL documentation for details.
  5. tables:
  6. - name: Rides --表名
  7. type: source --表类型 soruce为读入型源表,sink为写入型目标表(source表不存储真实的数据,sink表存储真实数据存储在外部依赖如mysql,kafka等)
  8. update-mode: append --更新方式 append 或者 update(Update 流只能写入支持更新的外部存储,如 MySQL, HBase。Append 流可以写入任意地存储,不过一般写入日志类型的系统,如 Kafka。)
  9. schema: --映射 目标表的字段及类型,此处字段和类型与format处的字段对应
  10. - name: rideId
  11. type: LONG
  12. - name: taxiId
  13. type: LONG
  14. - name: isStart
  15. type: BOOLEAN
  16. - name: lon
  17. type: FLOAT
  18. - name: lat
  19. type: FLOAT
  20. - name: rideTime -- 输出字段由eventTime变更为rideTime ,依据timestamp类型字段将其设为时间属性rowTime
  21. type: TIMESTAMP
  22. rowtime:
  23. timestamps:
  24. type: "from-field" --时间戳字段获取方式 :来自源表字段
  25. from: "eventTime" --时间戳字段 :源表的时间戳字段
  26. watermarks: --水印
  27. type: "periodic-bounded" --定义周期性水印
  28. delay: "60000" --最大延迟
  29. - name: psgCnt
  30. type: INT
  31. connector: --连接器
  32. property-version: 1
  33. type: kafka --连接kafka
  34. version: universal --0.11版本以上选择 universal
  35. topic: Rides --消费的topic名称
  36. startup-mode: earliest-offset --消费方式 earliest-offset从头开始消费数据 latest-offset消费最新数据
  37. properties: --设置zk,kafka端口及IP地址
  38. - key:
  39. value: zookeeper:2181
  40. - key:
  41. value: kafka:9092
  42. - key: group.id --设置消费者组
  43. value: testGroup
  44. format: --解析数据格式化
  45. property-version: 1
  46. type: json --此处解析数据类型是json格式,与上面字段映射一样
  47. schema: "ROW(rideId LONG, isStart BOOLEAN, eventTime TIMESTAMP, lon FLOAT, lat FLOAT, psgCnt INT, taxiId LONG)"
  48. - name: Fares
  49. type: source
  50. update-mode: append
  51. schema:
  52. - name: rideId
  53. type: LONG
  54. - name: payTime
  55. type: TIMESTAMP
  56. rowtime:
  57. timestamps:
  58. type: "from-field"
  59. from: "eventTime"
  60. watermarks:
  61. type: "periodic-bounded"
  62. delay: "60000"
  63. - name: payMethod
  64. type: STRING
  65. - name: tip
  66. type: FLOAT
  67. - name: toll
  68. type: FLOAT
  69. - name: fare
  70. type: FLOAT
  71. connector:
  72. property-version: 1
  73. type: kafka
  74. version: universal
  75. topic: Fares
  76. startup-mode: earliest-offset
  77. properties:
  78. - key:
  79. value: zookeeper:2181
  80. - key:
  81. value: kafka:9092
  82. - key: group.id
  83. value: testGroup
  84. format:
  85. property-version: 1
  86. type: json
  87. schema: "ROW(rideId LONG, eventTime TIMESTAMP, payMethod STRING, tip FLOAT, toll FLOAT, fare FLOAT)"
  88. - name: DriverChanges
  89. type: source
  90. update-mode: append
  91. schema:
  92. - name: taxiId
  93. type: LONG
  94. - name: driverId
  95. type: LONG
  96. - name: usageStartTime
  97. type: TIMESTAMP
  98. rowtime:
  99. timestamps:
  100. type: "from-field"
  101. from: "eventTime"
  102. watermarks:
  103. type: "periodic-bounded"
  104. delay: "60000"
  105. connector:
  106. property-version: 1
  107. type: kafka
  108. version: universal
  109. topic: DriverChanges
  110. startup-mode: earliest-offset
  111. properties:
  112. - key:
  113. value: zookeeper:2181
  114. - key:
  115. value: kafka:9092
  116. - key: group.id
  117. value: testGroup
  118. format:
  119. property-version: 1
  120. type: json
  121. schema: "ROW(eventTime TIMESTAMP, taxiId LONG, driverId LONG)"
  122. - name: Drivers
  123. type: temporal-table
  124. history-table: DriverChanges
  125. primary-key: taxiId
  126. time-attribute: usageStartTime
  127. - name: Sink_TenMinPsgCnt -- 表名(外部存储系统 如kakfa的topic,或者mysql的表名
  128. type: sink-table -- 表类型 soruce为读入型源表,sink为写入型目标表
  129. schema:
  130. - name: cntStart --要输出的目标字段名称 类型
  131. type: STRING
  132. - name: cntEnd
  133. type: STRING
  134. - name: cnt
  135. type: INT
  136. update-mode: append
  137. connector:
  138. property-version: 1
  139. type: kafka
  140. version: universal
  141. topic: Sink_TenMinPsgCnt -- 输出的topic名称
  142. properties:
  143. - key:
  144. value: zookeeper:2181
  145. - key:
  146. value: kafka:9092
  147. - key: group.id
  148. value: testGroup
  149. format:
  150. property-version: 1
  151. type: json
  152. schema: "ROW(cntStart STRING,cntEnd STRING,cnt INT)" -- 此处为输出的kafka的字段,中间的字段由sql加工别名转换为输出字段,注:字段个数,类型,顺序要与上面schema一摸一样
  153. functions: -- 函数定义
  154. - name: isInNYC
  155. from: class
  156. class: .sql_training.
  157. - name: toAreaId
  158. from: class
  159. class: .sql_training.
  160. - name: toCoords
  161. from: class
  162. class: .sql_training.
  163. ==============================================================================
  164. **Execution properties**
  165. ==============================================================================
  166. Execution properties allow for changing the behavior of a table program.
  167. execution:
  168. planner: blink # using the Blink planner
  169. type: streaming # 'batch' or 'streaming' execution
  170. result-mode: table # 'changelog' or 'table' presentation of results
  171. parallelism: 1 # parallelism of the program
  172. max-parallelism: 128 # maximum parallelism
  173. min-idle-state-retention: 0 # minimum idle state retention in ms
  174. max-idle-state-retention: 0 # maximum idle state retention in ms
  175. ==============================================================================
  176. **Deployment properties**
  177. ==============================================================================
  178. Deployment properties allow for describing the cluster to which table
  179. programs are submitted to.
  180. deployment:
  181. type: standalone # only the 'standalone' deployment is supported
  182. response-timeout: 5000 # general cluster communication timeout in ms
  183. gateway-address: "" # (optional) address from cluster to gateway
  184. gateway-port: 0 # (optional) port from cluster to gateway

复制代码