前提环境
首先需要各节点机器上需要有Java环境,如果没有,请自行进行安装操作。
前往Flink官网中下载Downloads | Apache Flink进行Flink包的下载,本次我选择的版本为1.20版本。
本地环境
单机环境部署
1. 解压安装
# 将文件上传到目录中,并解压
tar -xzvf flink-1.20.0-bin-scala_2.12.tgz
2. 启动Flink
启动单机版本的Flink
cd flink-1.20.0
bin/start-cluster.sh
# 请注意不能使用sh start-cluster.sh,会直接报错
# 启动完毕后,可直接查看jps进程

Flink提供了WEB界面可用于直观的管理Flink集群,访问端口为8081,
注意:将Flink配置文件flink-conf.yaml,将localhost改为0.0.0.0,修改后重启服务使用ip地址访问。
3. 启动测试案例
集群环境
Flink运行时由两种类型的进程组成:一个JobManager(作业管理器)和一个或者多个TaskManager(任务管理器)
可以通过多种方式启动JobManager和TaskManager:直接在机器上作为standalone集群启动、在容器中启动或者在yarn环境下启动。
工作流程:flink代码在本地会被构建一个数据流程图DataFlow Graph,之后会将这个DataFlowGraph提交给JobManager提交给JobManager并被拆分为一个一个的task,这些task会被发送到TaskManager中TaskSlot执行,TaskManager也会返回Task的状态信息给JobManager。
节点说明:
JobManger:决定合适调度下一个task,对完成的task或执行失败做出反应、协调checkPoint,并且协调从失败中恢复等。
TaskManagers:执行作业流的task、并且缓存和交换数据流。
必须始终至少有一个TaskManager,在taskmanager中资源调度的最小单位是taskSlot,taskSlot的数量表示并发处理task的数量,一个taskslot中可以执行多个算子。
Standalone模式部署
Standalone Cluster模式是Flink自带的不依赖于其他外部环境的一种搭建模式。在此运行模式下,所有Flink组件(JobManager、TaskManager)都在集群中运行,形成一个Flink集群。
前置条件
使用该模式下需要在三个节点下配置SSH免密登录后,再陆续进行以下步骤。一台Master,两台Slave。
部署步骤
修改conf/flink-conf.yaml中jobmanager节点的通讯地址为master节点。
jobmanager.rpc.address: master
修改conf/slave配置文件,将slave,slavee,配置为slave节点。
slave
slavee
配置完毕后之后将Flink安装包分别分发到其余两台机器上。
scp -r /usr/app/flink-1.9.1 hadoop002:/usr/app
scp -r /usr/app/flink-1.9.1 hadoop003:/usr/app
在master节点上使用与单机模式相同的命令来启动集群
/bin/start-cluster.sh
# 启动Flink测试实例
./bin/flink run ./examples/streaming/TopSpeedWindowing.jar
# 停止Flink集群
./bin/stop-cluster.sh
启动完毕后使用JPS命令或者通过web端来判断是否启动成功。
可选配置
在配置文件选项中,还存在其余配置信息,主要如下:
-
**jobmanager.heap.size:**JobManager 的 JVM 堆内存大小,默认为 1024m
-
**taskmanager.heap.size:**Taskmanager 的 JVM 堆内存大小,默认为 1024m
-
**taskmanager.numberOfTaskSlots:**Taskmanager 上 slots 的数量,通常设置为 CPU 核心的数量,或其一半。
-
**parallelism.default:**任务默认的并行度。
-
**io.tmp.dirs:**存储临时文件的路径,如果没有配置,则默认采用服务器的临时目录,如 LInux 的
/tmp
Flink On Yarn模式部署
本质为:将flink任务提交到yarn上运行。客户端将Flink应用提交给Yarn的ResourceManager,Yarn的ResouceManager会向Yarn的NodeManager申请容器,在这些容器上,Flink会部署JobManager和TaskManager的实例,从而启动集群。flink会根据运行在JobManager上的作业所需要的Slot数量动态分配TaskManager资源。
环境描述
-
3台Liunx服务器(node1,node2,node3)
-
节点间SSH免密互通互信
-
统一JDK版本(暂时考虑JDK8)
需要注意的是: 现在Flink1.20版本下并不支持JDK8
前置条件
1. 主机名与网络配置
# 注意 所有节点均要执行
sudo hostnamectl set-hostname node1
echo "192.168.1.101 node1" | sudo tee -a /etc/hosts
echo "192.168.1.102 node2" | sudo tee -a /etc/hosts
echo "192.168.1.103 node3" | sudo tee -a /etc/hosts
2. 创建节点普通用户
# 创建用户
useradd flink
3. SSH免密登录
# 在Node1生成密钥并分发
ssh-keygen -t rsa
ssh-copy-id node1 # 密码认证完毕后,重复操作到node2,node3
chmod 700 ~/.ssh && chmod 600 ~/.ssh/*
# 直接键入ssh node2验证是否需要密码登录
4. JDK环境安装
这里就不过多介绍,请自行安装
Hadoop/Yarn集群部署
前提需要搭建Hadoop集群环境,请查看[Hadoop环境搭建]
Flink集群部署
1. 下载安装Flink
wget https://dlcdn.apache.org/flink/flink-1.17.2/flink-1.17.2-bin-scala_2.12.tgz
tar -zxvf flink-1.18.0-bin-scala_2.12.tgz -C /app/flink
2. 配置Yarn集成
# 设置Hadoop配置路径
vim /flink/conf/flink-conf.yml
export HADOOP_CONF_DIR=hadoop/etc/hadoop
3. 提交测试任务
# 提交WordCount到YARN:
/opt/flink/bin/flink run -m yarn-cluster -yn 2 -ys 2 \
/opt/flink/examples/batch/WordCount.jar
可以通过yarn logs -applicationId <ApplicationId>
也可以直接访问Flink Web UI
历史服务器
运行Flink Job的集群一旦停止,只能去Yarn或本地磁盘上查看日志,不在可以查看作业挂掉之前的运行的WebUI,很难清楚知道作业在挂的那一刻到底发生了什么。
Flink提供了历史服务器,用来在相应的Flink集群关闭后查询已完成作业的统计信息。通过History server我们可以查询这些已完成作业的统计信息,无论是正常退出还是异常退出。
此外、他对外提供了Rest API,它接受HTTP请求并使用JSON数据进行响应。Flink任务停止后,JobManager会将已经完成任务的统计信息进行存档,History Server进程则在任务停止后可以对任务统计信息进行查询,比如:最后一次的CheckPoint、任务运行时的相关配置。
修改配置
// 添加存储目录
hadoop fs -mkdir -p /logs/flink-job
启动与停止
bin/historyserver.sh start
bin/historyserver.sh stop
Flink on Yarn HA方案
前提环境准备
这里按照上述环境准备三台服务器。
-
配置完毕JDK
-
配置Zookeeper集群组件
-
配置完毕HADOOP HA方式
-
三节点dfs、yarn环境已启动
搭建步骤
第一步:准备文件
wget https://dlcdn.apache.org/flink/flink-1.17.2/flink-1.17.2-bin-scala_2.12.tgz
tar -zxvf flink-1.17.2-bin-scala_2.12.tgz -C /data/app/software/flink
第二步:配置核心文件
修改Master文件
cd /data/app/software/flink/conf/master
node1:8081
修改work文件
cd /data/app/software/flink/conf/work
node1
node2
node3
修改flink-conf.yaml文件
################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
#==============================================================================
# Common
#==============================================================================
# The external address of the host on which the JobManager runs and can be
# reached by the TaskManagers and any clients which want to connect. This setting
# is only used in Standalone mode and may be overwritten on the JobManager side
# by specifying the --host <hostname> parameter of the bin/jobmanager.sh executable.
# In high availability mode, if you use the bin/start-cluster.sh script and setup
# the conf/masters file, this will be taken care of automatically. Yarn
# automatically configure the host name based on the hostname of the node where the
# JobManager runs.
jobmanager.rpc.address: node1 # jobmanager的rpc地址,集群环境下固定,各节点绑定一个,此地址代表flink初始化启动默认
# The RPC port where the JobManager is reachable.
jobmanager.rpc.port: 6123
# The host interface the JobManager will bind to. By default, this is localhost, and will prevent
# the JobManager from communicating outside the machine/container it is running on.
# On YARN this setting will be ignored if it is set to 'localhost', defaulting to 0.0.0.0.
# On Kubernetes this setting will be ignored, defaulting to 0.0.0.0.
#
# To enable this, set the bind-host address to one that has access to an outside facing network
# interface, such as 0.0.0.0.
jobmanager.bind-host: 0.0.0.0
# The total process memory size for the JobManager.
#
# Note this accounts for all memory usage within the JobManager process, including JVM metaspace and other overhead.
jobmanager.memory.process.size: 1600m
# The host interface the TaskManager will bind to. By default, this is localhost, and will prevent
# the TaskManager from communicating outside the machine/container it is running on.
# On YARN this setting will be ignored if it is set to 'localhost', defaulting to 0.0.0.0.
# On Kubernetes this setting will be ignored, defaulting to 0.0.0.0.
#
# To enable this, set the bind-host address to one that has access to an outside facing network
# interface, such as 0.0.0.0.
taskmanager.bind-host: 0.0.0.0
# The address of the host on which the TaskManager runs and can be reached by the JobManager and
# other TaskManagers. If not specified, the TaskManager will try different strategies to identify
# the address.
#
# Note this address needs to be reachable by the JobManager and forward traffic to one of
# the interfaces the TaskManager is bound to (see 'taskmanager.bind-host').
#
# Note also that unless all TaskManagers are running on the same machine, this address needs to be
# configured separately for each TaskManager.
taskmanager.host: node1 # taskmanager的主机地址,根据集群节点进行配置
# The total process memory size for the TaskManager.
#
# Note this accounts for all memory usage within the TaskManager process, including JVM metaspace and other overhead.
taskmanager.memory.process.size: 1728m # taskmanager的运行内存
# To exclude JVM metaspace and overhead, please, use total Flink memory size instead of 'taskmanager.memory.process.size'.
# It is not recommended to set both 'taskmanager.memory.process.size' and Flink memory.
#
# taskmanager.memory.flink.size: 1280m
# The number of task slots that each TaskManager offers. Each slot runs one parallel pipeline.
taskmanager.numberOfTaskSlots: 1 # 设置默认taskmanager的槽数
# The parallelism used for programs that did not specify and other parallelism.
parallelism.default: 1 # 设置默认的并行度
# The default file system scheme and authority.
#
# By default file paths without scheme are interpreted relative to the local
# root file system 'file:///'. Use this to override the default and interpret
# relative paths relative to a different file system,
# for example 'hdfs://mynamenode:12345'
#
# fs.default-scheme
#==============================================================================
# High Availability
#==============================================================================
# The high-availability mode. Possible options are 'NONE' or 'zookeeper'.
#
# high-availability.type: zookeeper
# The path where metadata for master recovery is persisted. While ZooKeeper stores
# the small ground truth for checkpoint and leader election, this location stores
# the larger objects, like persisted dataflow graphs.
#
# Must be a durable file system that is accessible from all nodes
# (like HDFS, S3, Ceph, nfs, ...)
#
# high-availability.storageDir: hdfs:///flink/ha/
# The list of ZooKeeper quorum peers that coordinate the high-availability
# setup. This must be a list of the form:
# "host1:clientPort,host2:clientPort,..." (default clientPort: 2181)
#
# high-availability.zookeeper.quorum: localhost:2181
# ACL options are based on https://zookeeper.apache.org/doc/r3.1.2/zookeeperProgrammers.html#sc_BuiltinACLSchemes
# It can be either "creator" (ZOO_CREATE_ALL_ACL) or "open" (ZOO_OPEN_ACL_UNSAFE)
# The default value is "open" and it can be changed to "creator" if ZK security is enabled
#
# high-availability.zookeeper.client.acl: open
# 设置Flink的高可用
high-availability: zookeeper
high-availability.zookeeper.quorum: node1:2181,node2:2181,node3:2181
high-availability.zookeeper.path.root: /flink
high-availability.storageDir: hdfs://mycluster/flink/ha # 文件需要创建
#==============================================================================
# Fault tolerance and checkpointing
#==============================================================================
# The backend that will be used to store operator state checkpoints if
# checkpointing is enabled. Checkpointing is enabled when execution.checkpointing.interval > 0.
#
# Execution checkpointing related parameters. Please refer to CheckpointConfig and ExecutionCheckpointingOptions for more details.
#
# execution.checkpointing.interval: 3min
# execution.checkpointing.externalized-checkpoint-retention: [DELETE_ON_CANCELLATION, RETAIN_ON_CANCELLATION]
# execution.checkpointing.max-concurrent-checkpoints: 1
# execution.checkpointing.min-pause: 0
# execution.checkpointing.mode: [EXACTLY_ONCE, AT_LEAST_ONCE]
# execution.checkpointing.timeout: 10min
# execution.checkpointing.tolerable-failed-checkpoints: 0
# execution.checkpointing.unaligned: false
#
# Supported backends are 'hashmap', 'rocksdb', or the
# <class-name-of-factory>.
#
# state.backend.type: hashmap
# Directory for checkpoints filesystem, when using any of the default bundled
# state backends.
#
# state.checkpoints.dir: hdfs://namenode-host:port/flink-checkpoints
# Default target directory for savepoints, optional.
#
# state.savepoints.dir: hdfs://namenode-host:port/flink-savepoints
# Flag to enable/disable incremental checkpoints for backends that
# support incremental checkpoints (like the RocksDB state backend).
#
# state.backend.incremental: false
# The failover strategy, i.e., how the job computation recovers from task failures.
# Only restart tasks that may have been affected by the task failure, which typically includes
# downstream tasks and potentially upstream tasks if their produced data is no longer available for consumption.
jobmanager.execution.failover-strategy: region
# 配置状态后端
state.backend: rocksdb
state.checkpoints.dir: hdfs://mycluster/flink/checkpoints # 检查点存储目录
state.savepoints.dir: hdfs://mycluster/flink/savepoints # 保存点存储目录
state.backend.rocksdb.localdir: /data/flink/rocksdb # RocksDB 本地存储目录
#==============================================================================
# Rest & web frontend
#==============================================================================
# The port to which the REST client connects to. If rest.bind-port has
# not been specified, then the server will bind to this port as well.
#
#rest.port: 8081
# The address to which the REST client will connect to
#
rest.address: localhost
# Port range for the REST and web server to bind to.
#
#rest.bind-port: 8080-8090
# The address that the REST & web server binds to
# By default, this is localhost, which prevents the REST & web server from
# being able to communicate outside of the machine/container it is running on.
#
# To enable this, set the bind address to one that has access to outside-facing
# network interface, such as 0.0.0.0.
#
rest.bind-address: 0.0.0.0 # 如果后续不能访问web程序,需要将绑定地址改为0.0.0.0
# Flag to specify whether job submission is enabled from the web-based
# runtime monitor. Uncomment to disable.
#web.submit.enable: false
# Flag to specify whether job cancellation is enabled from the web-based
# runtime monitor. Uncomment to disable.
#web.cancel.enable: false
#==============================================================================
# Advanced
#==============================================================================
# Override the directories for temporary files. If not specified, the
# system-specific Java temporary directory (java.io.tmpdir property) is taken.
#
# For framework setups on Yarn, Flink will automatically pick up the
# containers' temp directories without any need for configuration.
#
# Add a delimited list for multiple directories, using the system directory
# delimiter (colon ':' on unix) or a comma, e.g.:
# /data1/tmp:/data2/tmp:/data3/tmp
#
# Note: Each directory entry is read from and written to by a different I/O
# thread. You can include the same directory multiple times in order to create
# multiple I/O threads against that directory. This is for example relevant for
# high-throughput RAIDs.
#
# io.tmp.dirs: /tmp
# The classloading resolve order. Possible values are 'child-first' (Flink's default)
# and 'parent-first' (Java's default).
#
# Child first classloading allows users to use different dependency/library
# versions in their application than those in the classpath. Switching back
# to 'parent-first' may help with debugging dependency issues.
#
# classloader.resolve-order: child-first
# The amount of memory going to the network stack. These numbers usually need
# no tuning. Adjusting them may be necessary in case of an "Insufficient number
# of network buffers" error. The default min is 64MB, the default max is 1GB.
#
# taskmanager.memory.network.fraction: 0.1
# taskmanager.memory.network.min: 64mb
# taskmanager.memory.network.max: 1gb
classloader.check-leaked-classloader: false
#==============================================================================
# Flink Cluster Security Configuration
#==============================================================================
# Kerberos authentication for various components - Hadoop, ZooKeeper, and connectors -
# may be enabled in four steps:
# 1. configure the local krb5.conf file
# 2. provide Kerberos credentials (either a keytab or a ticket cache w/ kinit)
# 3. make the credentials available to various JAAS login contexts
# 4. configure the connector to use JAAS/SASL
# The below configure how Kerberos credentials are provided. A keytab will be used instead of
# a ticket cache if the keytab path and principal are set.
# security.kerberos.login.use-ticket-cache: true
# security.kerberos.login.keytab: /path/to/kerberos/keytab
# security.kerberos.login.principal: flink-user
# The configuration below defines which JAAS login contexts
# security.kerberos.login.contexts: Client,KafkaClient
#==============================================================================
# ZK Security Configuration
#==============================================================================
# Below configurations are applicable if ZK ensemble is configured for security
# Override below configuration to provide custom ZK service name if configured
# zookeeper.sasl.service-name: zookeeper
# The configuration below must match one of the values set in "security.kerberos.login.contexts"
# zookeeper.sasl.login-context-name: Client
#==============================================================================
# HistoryServer
#==============================================================================
# The HistoryServer is started and stopped via bin/historyserver.sh (start|stop)
# Directory to upload completed jobs to. Add this directory to the list of
# monitored directories of the HistoryServer as well (see below).
#jobmanager.archive.fs.dir: hdfs:///completed-jobs/
# The address under which the web-based HistoryServer listens.
#historyserver.web.address: 0.0.0.0
# The port under which the web-based HistoryServer listens.
#historyserver.web.port: 8082
# Comma separated list of directories to monitor for completed jobs.
#historyserver.archive.fs.dir: hdfs:///completed-jobs/
# Interval in milliseconds for refreshing the monitored directories.
#historyserver.archive.fs.refresh-interval: 10000
# 设置历史服务器,
jobmanager.archive.fs.dir: hdfs://mycluster/flink/completed-jobs
historyserver.web.address: 0.0.0.0
historyserver.web.port: 8082
historyserver.archive.fs.dir: hdfs://mycluster/flink/completed-jobs
historyserver.archive.fs.refresh-interval: 10000
第三步:启动
首先启动历史服务器
historyserver.sh start
historyserver.sh stop
提交任务
flink run -m yarn-cluster -yjm 1024 -ytm 1024 $FLINK_HOME/examples/batch/WordCount.jar
# 控制台会打印出单词统计信息,如果报错,请根据日志信息慢慢解决
问题总结
问题一:无法加载类加载器
问题原因为:hadoop3引用了异步线程来执行shutdown hook,该hook会在任务执行时运行,由于classloader已经释放,但是hook中依然持有该classloader而跑出异常,该异常不影响正常功能。
解决办法:在flink-conf.yaml中设置classloader.check-leaked-classloader: false
问题二:频繁出现failing over to rm2
问题原因:因为我的默认resourceManager被自动从节点一选举到节点二,所以一直在提示故障转移。可以忽略