12、Flink实战:容错机制(二)重启策略实例

示例代码如下:

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<String> lines = env.socketTextStream("192.168.***.****", 8888);

        //5. Transformation 数据转换
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = line.split(",");

                for (int i = 0; i < words.length; i++) {
                    if("error".equals(words[i])){
                        System.out.println(i/0);     // 会产生错误
                    }
                    collector.collect(Tuple2.of(words[i], 1));
                }
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = wordAndOne.keyBy(0).sum(1);

        //6. sink 打印输出
        summed.print();

        //7. 启动流计算
        env.execute("RestartStrategyReview");
    }
}

在flink输出次数为5后,输入error,报错重启,再次输入flink后统计次数是6.

*

*

版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: