Flink ValueState 实例

ValueState的使用比较简单,方法如下图

  • 用ValueStateDescriptor定义ValueState的描述器
  • value()方法获取值
  • update(T value)方法更新值

需求1:单词3秒未重复出现则输出该单词

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
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.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Random;

public class ValueStateTest {
    public static void main(String[] args) throws Exception {
        // 单词n秒不出现则输出
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.getConfig().setAutoWatermarkInterval(100l);

        DataStreamSource<Tuple2<String, Long>> tuple2DataStreamSource = env.addSource(new SourceFunction<Tuple2<String, Long>>() {

            boolean flag = true;

            @Override
            public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
                String[] str = {"王五", "吕子乔", "丽萨", "李四", "张三"};
                while (flag) {
                    int i = new Random().nextInt(4);
                    Thread.sleep(1000l);
                    ctx.collect(new Tuple2<String, Long>(str[i], System.currentTimeMillis()));
                }
            }

            @Override
            public void cancel() {
                flag = false;
            }
        });


        SingleOutputStreamOperator<Tuple2<String, Long>> tuple2SingleOutputStreamOperator = tuple2DataStreamSource.assignTimestampsAndWatermarks(WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                    @Override
                    public long extractTimestamp(Tuple2<String, Long> stringLongTuple2, long l) {
                        return stringLongTuple2.f1;
                    }
                }));

        tuple2SingleOutputStreamOperator.map(new MapFunction<Tuple2<String,Long>,Tuple2<String,Integer>>(){

            @Override
            public Tuple2<String, Integer> map(Tuple2<String, Long> stringLongTuple2) throws Exception {
                System.out.println("key:" + stringLongTuple2.f0 + " timestamp:" + stringLongTuple2.f1);
                return new Tuple2<String,Integer>(stringLongTuple2.f0,1);
            }
        }).keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                return stringIntegerTuple2.f0;
            }
        }).process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String,Long>>() {

            ValueState<Long> valueState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                ValueStateDescriptor<Long> valueStateDescriptor = new ValueStateDescriptor<Long>("valueState",Long.class);
                valueState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String,Long>> out) throws Exception {
                // 获取最后出现的时间戳
                Long lastTime = ctx.timestamp();
                // 定时时间
                Long timerTime = lastTime + (3 * 1000l);
                Long stateTime = valueState.value();
                // 更新state
                valueState.update(timerTime);
                // 注册定时器
                ctx.timerService().registerEventTimeTimer(timerTime);
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String,Long>> out) throws Exception {
                super.onTimer(timestamp, ctx, out);
                Long stateTime = valueState.value();
                // 如果定时时间=单词最后出现的时间戳+3s,则表明3s内没有出现过相同的单词,发往下游
                if(timestamp == stateTime){
                    out.collect(new Tuple2<String,Long>(ctx.getCurrentKey(),timestamp));
                }
            }
        }).print();

        env.execute("value-state");

    }
}

需求2:温差超过10度则报警

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
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.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Random;

public class ValueStateTest1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.getConfig().setAutoWatermarkInterval(100l);

        DataStreamSource<Tuple3<String, Integer, Long>> tuple2DataStreamSource = env.addSource(new SourceFunction<Tuple3<String, Integer, Long>>() {

            boolean flag = true;

            @Override
            public void run(SourceContext<Tuple3<String, Integer, Long>> ctx) throws Exception {
                String[] str = {"水阀1", "水阀2", "水阀3"};
                while (flag) {
                    int i = new Random().nextInt(3);
                    // 温度
                    int temperature = new Random().nextInt(100);
                    Thread.sleep(500l);
                    // 设备号、温度、事件时间
                    ctx.collect(new Tuple3<String, Integer, Long>(str[i], temperature, System.currentTimeMillis()));
                }
            }

            @Override
            public void cancel() {
                flag = false;
            }
        });

        SingleOutputStreamOperator<Tuple3<String, Integer, Long>> tuple2SingleOutputStreamOperator = tuple2DataStreamSource.assignTimestampsAndWatermarks(WatermarkStrategy.<Tuple3<String, Integer, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple3<String, Integer, Long>>() {
                    @Override
                    public long extractTimestamp(Tuple3<String, Integer, Long> stringIntegerLongTuple3, long l) {
                        return stringIntegerLongTuple3.f2;
                    }
                }));

        tuple2SingleOutputStreamOperator.map(new MapFunction<Tuple3<String, Integer, Long>,Tuple2<String,Integer>>(){

            @Override
            public Tuple2<String, Integer> map(Tuple3<String, Integer, Long> stringLongTuple2) throws Exception {
                System.out.println("key:" + stringLongTuple2.f0 + " tempertaur:" + stringLongTuple2.f1);
                return new Tuple2<String,Integer>(stringLongTuple2.f0,stringLongTuple2.f1);
            }
        }).keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                return stringIntegerTuple2.f0;
            }
        }).process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple3<String,Integer,Integer>>() {

            ValueState<Integer> valueState = null;

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

                // 设备号、上次温度、本次温度
                ValueStateDescriptor<Integer> valueStateDescriptor = new ValueStateDescriptor("valueState", Integer.class);
                valueState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple3<String, Integer, Integer>> out) throws Exception {
                // 初始化
                if(valueState.value() == null){
                    valueState.update(Integer.MIN_VALUE);
                }

                //获取上次温度
                int lastTemper = valueState.value();
                // 如果温差大于等于10,输出
                if(Math.abs(value.f1 - lastTemper) >= 10){
                    out.collect(new Tuple3<String,Integer, Integer>(value.f0,lastTemper,value.f1));
                }

                // 更新状态
                valueState.update(value.f1);
            }
        }).print();

        env.execute("value-state");
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
FlinkValueStateFlink状态编程的一种状态类型。它用于在算子的处理函数保存和访问一个单一的值。ValueState可以在算子的不同处理函数共享和访问,以便跨时间和事件保持状态。 使用ValueState,可以在算子的处理函数存储和更新一个值。这个值可以是任何类型,比如基本数据类型、自定义对象等。通过ValueState,算子可以在处理事件流时维护一些状态信息,从而实现一些有状态的计算逻辑。 要使用ValueState,首先需要在算子的运行时上下文获取一个ValueStateDescriptor对象,该对象指定了ValueState的名称和类型。然后,可以通过调用ValueStateDescriptor的getState方法来获取具体的ValueState对象。通过这个ValueState对象,可以访问和更新存储在其的值。 以下是一个示例代码片段,演示了如何在Flink使用ValueState: ```java // 导入所需的类 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.util.Collector; public class MyFlatMapFunction extends RichFlatMapFunction<Integer, String> { // 声明一个ValueState变量 private transient ValueState<Integer> countState; @Override public void open(Configuration parameters) throws Exception { // 初始化ValueState ValueStateDescriptor<Integer> descriptor = new ValueStateDescriptor<>("countState", Integer.class); countState = getRuntimeContext().getState(descriptor); } @Override public void flatMap(Integer value, Collector<String> out) throws Exception { // 获取当前状态值 Integer currentCount = countState.value(); if (currentCount == null) { currentCount = 0; } // 更新状态值 currentCount += value; countState.update(currentCount); // 输出结果 out.collect("Current count: " + currentCount); } } ``` 在上述代码,我们通过调用`getRuntimeContext().getState(descriptor)`获取了一个`ValueState<Integer>`对象,该对象用于存储和访问一个整数值。在`flatMap`函数,我们首先通过`countState.value()`获取当前状态值,然后根据业务逻辑更新状态值,并通过`countState.update(currentCount)`方法更新状态。最后,我们使用`out.collect`方法将结果输出。 这只是一个简单的示例,实际可以根据业务需求使用ValueState来实现更复杂的状态计算逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值