需求:
需要在某个特定时间段主动触发checkpoint,以保证sink数据对下游的时效性,虽然减小checkpoint时间就可以,但这无疑对stateBackend存储(如hdfs)造成压力。
以下尝试方案使用flink-1.13.1_scala2.12版本
提交checkpoint的代码逻辑主要处于 flink-runtime模块,主要处理类为"CheckpointCoordinator"
贴出部分方法:
scheduleTriggerWithDelay
// 可以看到这是一个异步方法,其主要使用定时器周期性(默认checkpoint值)的执行ScheduledTrigger()
private ScheduledFuture> scheduleTriggerWithDelay(long initDelay) {
return timer.scheduleAtFixedRate(
new ScheduledTrigger(), initDelay, baseInterval, TimeUnit.MILLISECONDS);
}
ScheduledTrigger
// 可以看到,这是实现了Runnable的一个线程
private final class ScheduledTrigger implements Runnable {
@Override
public void run() {
try {
triggerCheckpoint(true);
} catch (Exception e) {
LOG.error("Exception while triggering checkpoint for job {}.", job, e);
}
}
}
triggerCheckpoint
public CompletableFuturetriggerCheckpoint( CheckpointProperties props, @Nullable String externalSavepointLocation, boolean isPeriodic) { if (props.getCheckpointType().getPostCheckpointAction() == PostCheckpointAction.TERMINATE && !(props.isSynchronous() && props.isSavepoint())) { return FutureUtils.completedExceptionally( new IllegalArgumentException( "only synchronous savepoints are allowed to advance the watermark to MAX.")); } CheckpointTriggerRequest request = new CheckpointTriggerRequest(props, externalSavepointLocation, isPeriodic); chooseRequestToExecute(request).ifPresent(this::startTriggeringCheckpoint); return request.onCompletionPromise; }
由源码得知,flink设置定时器,按照checkpoint时间周期性的执行checkpoint线程。
2.向"CheckpointCoordinator"添加自定义定时器,在自定义时间段触发checkpoint动作修改 “scheduleTriggerWithDelay” 方法:
scheduleTriggerWithDelay
// 可以看到这是一个异步方法,其主要使用定时器周期性(默认checkpoint值)的执行ScheduledTrigger()
private ScheduledFuture> scheduleTriggerWithDelay(long initDelay) {
// 加入自定义计时器
checkPointOnCustomTime(new ScheduledTrigger());
return timer.scheduleAtFixedRate(
new ScheduledTrigger(), initDelay, baseInterval, TimeUnit.MILLISECONDS);
}
private void checkPointOnCustomTime(Runnable runable) {
// 执行周期
long daySpan = 24 * 60 * 60 * 1000L;
// 每天定时执行
long initDelay = getTimeMillis("00:05:00") - System.currentTimeMillis();
// 计算第一次执行的延时时间
// 如果已经过了执行时间,就推迟为下个周期执行
initDelay = initDelay > 0 ? initDelay : daySpan + initDelay;
// 使用 ScheduledThreadPoolExecutor创建只有一个线程的定时执行的线程池
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(runable,initDelay,daySpan, TimeUnit.MILLISECONDS);
}
private long getTimeMillis(String time) {
try {
DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
return curDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
3.复制"flink-runtime_2.12-1.13.1-shaded.jar"至flink客户端lib目录下,提交任务测试。


