import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
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.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import java.time.Duration;
/**
* 功能描述:事件时间和处理时间一起使用
*
*/
public class EventTimeAndProcessTime {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(2);
SingleOutputStreamOperator<Long> eventInput = env.socketTextStream("localhost", 9999)
.map(Long::valueOf);
KeyedStream<Long, Integer> keyedInputStream = eventInput.assignTimestampsAndWatermarks(WatermarkStrategy.<Long>forBoundedOutOfOrderness(Duration.ZERO)
.withTimestampAssigner(new SerializableTimestampAssigner<Long>() {
@Override
public long extractTimestamp(Long aLong, long l) {
return aLong;
}
}))
.keyBy(ele -> 1);
keyedInputStream
.window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
.process(new ProcessWindowFunction<Long, String, Integer, TimeWindow>() {
@Override
public void process(Integer integer, ProcessWindowFunction<Long, String, Integer, TimeWindow>.Context context, Iterable<Long> iterable, Collector<String> collector) throws Exception {
StringBuilder sb = new StringBuilder();
for (Long aLong : iterable) {
sb.append(aLong);
sb.append(" ");
}
collector.collect(sb.toString());
}
})
.print("process time : ");
keyedInputStream
.window(TumblingEventTimeWindows.of(Time.milliseconds(10)))
.process(new ProcessWindowFunction<Long, String, Integer, TimeWindow>() {
@Override
public void process(Integer integer, ProcessWindowFunction<Long, String, Integer, TimeWindow>.Context context, Iterable<Long> iterable, Collector<String> collector) throws Exception {
StringBuilder sb = new StringBuilder();
for (Long aLong : iterable) {
sb.append(aLong);
sb.append(" ");
}
collector.collect(sb.toString());
}
})
.print("event time : ");
env.execute();
}
}
flink中同时使用eventtime和processtime
于 2022-12-24 15:50:15 首次发布