示例代码如下:
1. 首先要开启checkpointing, 如 env.enableCheckpointing(5000);
2. 选择一种重启策略
//固定间隔重启:最多重启五次,重启间隔2000毫秒env.setRestartStrategy(RestartStrategies.fixedDelayRestart(5,2000));
//失败率:failureRate是每个测量时间间隔最大失败次数
//第二个参数failureInterval失败率测量的时间间隔; //第三个参数delayInterval是两次连续重启尝试的时间间隔env.setRestartStrategy(RestartStrategies.failureRateRestart(5,Time.of(5, TimeUnit.MINUTES),Time.of(10, TimeUnit.SECONDS)));
//无重启env.setRestartStrategy(RestartStrategies.noRestart());
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import java.util.concurrent.TimeUnit;public class RestartStrategyReview {public static void main(String[] args) throws Exception{//1.获取flink流计算的运行环境StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();//2. 开启checkpointing 只有开启了才会有重启策略,参数为周期(毫秒)env.enableCheckpointing(5000);//3. 设置重启策略//3.1 固定间隔重启:最多重启五次,重启间隔2000毫秒env.setRestartStrategy(RestartStrategies.fixedDelayRestart(5,2000));//3.2 失败率:failureRate是每个测量时间间隔最大失败次数//第二个参数failureInterval失败率测量的时间间隔; //第三个参数delayInterval是两次连续重启尝试的时间间隔
// env.setRestartStrategy(RestartStrategies.failureRateRestart(5,
// Time.of(5, TimeUnit.MINUTES),Time.of(10, TimeUnit.SECONDS)));//3.3 无重启
// env.setRestartStrategy(RestartStrategies.noRestart());//4. 连接数据源DataStreamSource lines = env.socketTextStream("192.168.***.****", 8888);//5. Transformation 数据转换SingleOutputStreamOperator> wordAndOne = lines.flatMap(new FlatMapFunction>() {@Overridepublic void flatMap(String line, Collector> collector) throws Exception {String[] words = line.split(",");for (int i = 0; i > summed = wordAndOne.keyBy(0).sum(1);//6. sink 打印输出summed.print();//7. 启动流计算env.execute("RestartStrategyReview");}
}
在flink输出次数为5后,输入error,报错重启,再次输入flink后统计次数是6.