flink流媒体示例,生成自己的数据

r7s23pms  于 2021-06-26  发布在  Flink
关注(0)|答案(1)|浏览(298)

早些时候,我问了一个简单的helloworld的例子。这给了我一些很好的例子!
然而,我想问一个更'流'的例子,我们产生一个输入值每秒钟。这在理想情况下是随机的,但即使每次都是相同的值也可以。
我们的目标是获得一个没有/很少外部接触的“移动”流。
因此我的问题是:

如何在没有外部依赖的情况下显示flink实际的流数据?

我发现如何在外部生成数据并将其写入kafka,或者监听公共源代码来显示这一点,但是我正在尝试以最小的依赖性来解决它(比如从nifi中的generateflowfile开始)。

pbpqsu0x

pbpqsu0x1#

下面是一个例子。这是一个如何使源和汇可插入的示例。其思想是,在开发中,您可以使用随机源并打印结果;在测试中,您可以使用硬连线的输入事件列表并在列表中收集结果;在生产中,您可以使用真实的源和汇。
工作如下:

/*
 * Example showing how to make sources and sinks pluggable in your application code so
 * you can inject special test sources and test sinks in your tests.
 */

public class TestableStreamingJob {
    private SourceFunction<Long> source;
    private SinkFunction<Long> sink;

    public TestableStreamingJob(SourceFunction<Long> source, SinkFunction<Long> sink) {
        this.source = source;
        this.sink = sink;
    }

    public void execute() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<Long> LongStream =
                env.addSource(source)
                        .returns(TypeInformation.of(Long.class));

        LongStream
                .map(new IncrementMapFunction())
                .addSink(sink);

        env.execute();
    }

    public static void main(String[] args) throws Exception {
        TestableStreamingJob job = new TestableStreamingJob(new RandomLongSource(), new PrintSinkFunction<>());
        job.execute();
    }

    // While it's tempting for something this simple, avoid using anonymous classes or lambdas
    // for any business logic you might want to unit test.
    public class IncrementMapFunction implements MapFunction<Long, Long> {

        @Override
        public Long map(Long record) throws Exception {
            return record + 1 ;
        }
    }

}

这是你的答案 RandomLongSource :

public class RandomLongSource extends RichParallelSourceFunction<Long> {

    private volatile boolean cancelled = false;
    private Random random;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        random = new Random();
    }

    @Override
    public void run(SourceContext<Long> ctx) throws Exception {
        while (!cancelled) {
            Long nextLong = random.nextLong();
            synchronized (ctx.getCheckpointLock()) {
                ctx.collect(nextLong);
            }
        }
    }

    @Override
    public void cancel() {
        cancelled = true;
    }
}

相关问题