flink使用ListState实现KeyedState

测试数据

user1,A
user1,B
user1,C

user2,A
user2,B
user2,D
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Zhang
 * @Description:
 * @Date: Created in 22:20 2021/12/25
 * @Modified By:
 */
public class ListStateDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //开启checkpoint, 每10s进行一次checkpoint, 开启后默认使用无限重启策略
        env.enableCheckpointing(10000);

        //开启失败率重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(
                3, // max failures per unit
                Time.of(30, TimeUnit.SECONDS), //time interval for measuring failure rate
                Time.of(3, TimeUnit.SECONDS) // delay

        ));

        DataStreamSource<String> lines = env.socketTextStream("doitedu03", 8888);


        SingleOutputStreamOperator<Tuple2<String,String>> tpStream = lines.flatMap(new FlatMapFunction<String, Tuple2<String,String>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String,String>> collector) throws Exception {
                String[] sp = value.split(",");
                if (sp[0].equals("error")){
                    throw  new RuntimeException("出现错误了!!!");
                }
                collector.collect(Tuple2.of(sp[0],sp[1]));
            }
        });

        KeyedStream<Tuple2<String, String>, String> keyed = tpStream.keyBy(t -> t.f0);



        keyed.process(new KeyedProcessFunction<String, Tuple2<String, String>, Tuple2<String,List<String>>>() {


            private transient ListState<String> listState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //定义一个state描述器
                ListStateDescriptor<String> listStateDescriptor = new ListStateDescriptor<>("list-state", String.class);
                //初始化或者恢复历史状态
                listState = getRuntimeContext().getListState(listStateDescriptor);

            }

            @Override
            public void processElement(Tuple2<String, String> input, Context context, Collector<Tuple2<String, List<String>>> collector) throws Exception {
                String user = input.f0;
                String event = input.f1;
                listState.add(event);

                ArrayList<String> eventList = new ArrayList<>();

                Iterable<String> iter = listState.get();
                for (String e : iter) {
                    eventList.add(e);
                }
                collector.collect(Tuple2.of(user,eventList));

            }
        }).print();


        env.execute();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值