1 package ontime; 2 3 import com.Sensor; 4 import org.apache.flink.api.common.state.ValueState; 5 import org.apache.flink.api.common.state.ValueStateDescriptor; 6 import org.apache.flink.api.java.tuple.Tuple; 7 import org.apache.flink.configuration.Configuration; 8 import org.apache.flink.streaming.api.functions.KeyedProcessFunction; 9 import org.apache.flink.util.Collector; 10 11 public class MyProcess extends KeyedProcessFunction<Tuple, Sensor,String> { 12 13 ValueState<Double> tempState; 14 ValueState<Long> timeState; 15 private Integer tempInterval; 16 public MyProcess(Integer tempInterval){ 17 this.tempInterval=tempInterval; 18 } 19 20 @Override 21 public void open(Configuration parameters) throws Exception { 22 tempState=getRuntimeContext().getState(new ValueStateDescriptor<Double>("last-temp",Double.class)); 23 timeState=getRuntimeContext().getState(new ValueStateDescriptor<Long>("last-time",Long.class)); 24 25 } 26 27 @Override 28 public void processElement(Sensor sensor, Context context, Collector<String> collector) throws Exception { 29 Double lastTemp = tempState.value(); 30 Long lastTime = timeState.value(); 31 if (sensor.getSensorTemp()>70 && lastTime==null){ 32 long times = context.timerService().currentProcessingTime() + tempInterval * 1000L; 33 context.timerService().registerProcessingTimeTimer(times); 34 timeState.update(times); 35 }else if (sensor.getSensorTemp()<70 && lastTime!=null ) { 36 context.timerService().deleteProcessingTimeTimer(lastTime); 37 timeState.clear(); 38 } 39 tempState.update(sensor.getSensorTemp()); 40 41 } 42 43 @Override 44 public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception { 45 System.out.println("sensor:"+ctx.getCurrentKey().getField(0)+"温度连续3秒大于70度"); 46 } 47 48 @Override 49 public void close() throws Exception { 50 timeState.clear(); 51 } 52 }
1 package ontime; 2 3 import com.MySource; 4 import com.Sensor; 5 import org.apache.flink.streaming.api.datastream.DataStreamSource; 6 import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; 7 import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; 8 9 //StateTest 10 public class StateTest { 11 public static void main(String[] args) throws Exception { 12 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); 13 //并行度 14 env.setParallelism(1); 15 //自定义数据源 生成70度左右的传感器数据 16 DataStreamSource<Sensor> source = env.addSource(new MySource(70)); 17 //打印 18 source.print(); 19 //自定义process 3s间隔 20 SingleOutputStreamOperator<String> out = source.keyBy("sensorId").process(new MyProcess(3)); 21 //报警 22 out.print(); 23 //执行 24 env.execute(); 25 } 26 }