apache beam KafkaIO的使用(流處理IO)

目錄:apache beam 個人使用經驗總結目錄和入門指導(Java)
這裏我以下面這個爲例,弄1個demo
在這裏插入圖片描述
第一步建立option和pipeline

        PipelineOptions kafkaOption = PipelineOptionsFactory.fromArgs(args).withoutStrictParsing().as(PipelineOptions.class);
        Pipeline pipeline = Pipeline.create(kafkaOption);

如何消費beamKafaTest主題裏的數據

首先要建立1個kafkaRead對象

        KafkaIO.Read<String, String> kafkaRead =
                KafkaIO.<String, String>read()
                .withBootstrapServers("{bootip}")
                .withTopic("beamKafkaTest")
                .withKeyDeserializer(StringDeserializer.class)
                .withValueDeserializer(StringDeserializer.class);

boostrapServer的ip和端口視各自集羣上的kafka配置而定
接着用apply進行組裝,組裝時要加上withoutMetaData作爲最終的建立操作

PCollection<KV<String, String>> pKv = pipeline.apply(kafkaRead.withoutMetadata());

設置窗口

數據集裏的KV<String,String>指的就是消費的kafkaRecord裏的key和value,這裏直接幫我們轉成KV了

  • 我只需要裏面的value整數值,因此需要把Key-Value轉成Value。
  • 同時我們希望以每5秒作爲1個窗口將結果進行收集,因此需要使用windows類進行組裝
  • 同時要把5秒內的結果做個總和作爲輸出,要使用Sum這個類,並且要加上withoutDefaults,否則無法進行流處理。
        PCollection<Integer> pIntSum = pKv.apply(MapElements.via(new SimpleFunction<KV<String, String>, Integer>() {
            @Override
            public Integer apply(KV<String, String> input) {
                return Integer.valueOf(input.getValue());
            }
        }))
                .apply(Window.into(FixedWindows.of(Duration.standardSeconds(5))))
                .apply(Sum.integersGlobally().withoutDefaults());

生產消息到beamPrint主題

生產消息就比較簡單了, 注意要先map成KV對象,才能使用KafkaIO.write

pIntSum.apply(MapElements.<Integer, KV<Integer, String>>via(new SimpleFunction<Integer, KV<Integer, String>>() {
            // v轉kv
            @Override
            public KV<Integer, String> apply(Integer input) {
                return KV.of((input!=null?input:0), "answer=" + (input!=null?input:0));
            }
        }))
                .apply(KafkaIO.<Integer, String>write()
                        .withBootstrapServers("{bootip}")
                        .withTopic("beamPrint")
                        .withKeySerializer(IntegerSerializer.class)
                        .withValueSerializer(StringSerializer.class));

測試

啓動beamDemo程序,然後用Kafka客戶端腳本打開生產者和消費者。
5秒內在beamKafkaTest中輸入1、2、3
在這裏插入圖片描述
然後可在beamPrint中看到輸出:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章