Flink教程(15) Keyed State状态管理之ListState使用 ValueState实现

系列文章

Flink教程(13) Keyed State状态管理之ValueState的使用 温差报警
Flink教程(14) Keyed State状态管理之MapState使用案例
Flink教程(15) Keyed State状态管理之ListState使用 ValueState实现
Flink教程(16) Keyed State状态管理之ReducingState使用案例 求最大值
Flink教程(17) Keyed State状态管理之AggregatingState使用案例 求平均值

一、ListState的方法

  • get()方法获取值
  • add(IN value),addAll(List values)方法更新值
  • update(List values) 用新List 替换 原来的List
  • clear() 清空List,List还存在,但是没有元素
    在这里插入图片描述

二、代码案例

1. 需求

记录每个人的历史操作信息,例如输入

1,login
1,buy something
1,logout
2,login
2,click book
1,login

要输出

(1,[login])
(1,[login, buy something])
(1,[login, buy something, logout])
(2,[login])
(2,[login, click book])
(1,[login, buy something, logout, login])

2. 主体

public class Test03_ListState {

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

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<String> source = env.socketTextStream(BaseConstant.URL, BaseConstant.PORT);

        SingleOutputStreamOperator<Tuple2<String, String>> dataStream = source
                .map(new MapFunction<String, Tuple2<String, String>>() {

                    @Override
                    public Tuple2<String, String> map(String value) throws Exception {
                        String[] split = value.split(",");
                        if (split != null && split.length == 2) {
                            return Tuple2.of(split[0], split[1]);
                        }
                        return null;
                    }
                });


        dataStream
                .keyBy(t -> t.f0)
                .process(new MyKeyedProcessFunction())
                .print();

        env.execute();
    }
}

3. 处理方法

public static class MyKeyedProcessFunction extends KeyedProcessFunction<String, Tuple2<String, String>, Tuple2<String, List<String>>> {

    //之前的操作记录
    private transient ListState<String> listState;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        ListStateDescriptor<String> recentOperatorsDescriptor = new ListStateDescriptor<String>(
                "recent-operator",
                String.class);

        listState = getRuntimeContext().getListState(recentOperatorsDescriptor);
    }

    @Override
    public void processElement(Tuple2<String, String> value, Context ctx, Collector<Tuple2<String, List<String>>> out) throws Exception {

        String action = value.f1;

        listState.add(action);

        Iterable<String> iterable = listState.get();
        ArrayList<String> events = new ArrayList<>();

        for (String actionName : iterable) {
            events.add(actionName);
        }

        out.collect(Tuple2.of(value.f0, events));

        listState.update(events);

    }
}

4. 运行结果

在这里插入图片描述

5. 用ValueState实现ListState

用ValueState实现ListState可以实现ListState,只要ValueState里装的是List

public static class MyKeyedProcessFunction extends KeyedProcessFunction<String, Tuple2<String, String>, Tuple2<String, List<String>>> {

    //之前的操作记录
    private transient ValueState<List<String>> listState;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        ValueStateDescriptor<List<String>> recentOperatorsDescriptor = new ValueStateDescriptor<List<String>>(
                "recent-operator",
                TypeInformation.of(new TypeHint<List<String>>(){}));

        listState = getRuntimeContext().getState(recentOperatorsDescriptor);
    }

    @Override
    public void processElement(Tuple2<String, String> value, Context ctx, Collector<Tuple2<String, List<String>>> out) throws Exception {

        String action = value.f1;

        List<String> lst = listState.value();

        if (lst == null){
            lst = new ArrayList<>();
        }
        lst.add(action);

        listState.update(lst);

        out.collect(Tuple2.of(value.f0, listState.value()));
    }
}
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Flink中,ValueState是一种状态类型,可以用于存储单个值。它通常用于对输入流中的某些值进行聚合或累积计算,例如计算平均值或求和。以下是使用ValueState的示例代码: ``` // 导入必要的库 import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.api.common.state.ValueState; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.configuration.Configuration; import org.apache.flink.util.Collector; // 实现一个 RichFlatMapFunction public class MyFlatMapFunction extends RichFlatMapFunction<Integer, Integer> { private transient ValueState<Integer> sumState; @Override public void open(Configuration config) { // 初始化 ValueState ValueStateDescriptor<Integer> sumStateDescriptor = new ValueStateDescriptor<>("sum", Integer.class); sumState = getRuntimeContext().getState(sumStateDescriptor); } @Override public void flatMap(Integer value, Collector<Integer> out) throws Exception { // 从 ValueState 中获取之前的累加结果 Integer sum = sumState.value(); if (sum == null) { sum = 0; } // 进行累加计算 sum += value; // 更新 ValueState 中的值 sumState.update(sum); // 输出结果 out.collect(sum); } } ``` 在上面的示例中,我们实现了一个 RichFlatMapFunction,使用ValueState对输入流中的整数进行累加计算,并将结果输出。在open()方法中,我们初始化了一个名为“sum”的ValueState。在flatMap()方法中,我们首先从ValueState中获取之前的累加结果,如果ValueState中没有值,则将sum初始化为0。然后,我们进行累加计算,并更新ValueState中的值。最后,我们将累加结果输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为啥总是用户昵称已存在

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值