最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java lambda表達(dá)式實(shí)現(xiàn)Flink WordCount過(guò)程解析

 更新時(shí)間:2020年02月04日 11:55:20   作者:M。  
這篇文章主要介紹了Java lambda表達(dá)式實(shí)現(xiàn)Flink WordCount過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了Java lambda表達(dá)式實(shí)現(xiàn)Flink WordCount過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

本篇我們將使用Java語(yǔ)言來(lái)實(shí)現(xiàn)Flink的單詞統(tǒng)計(jì)。

代碼開發(fā)

環(huán)境準(zhǔn)備

導(dǎo)入Flink 1.9 pom依賴

<dependencies>
    <dependency>
      <groupId>org.apache.flink</groupId>
      <artifactId>flink-java</artifactId>
      <version>1.9.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.flink</groupId>
      <artifactId>flink-streaming-java_2.11</artifactId>
      <version>1.9.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.7</version>
    </dependency>
  </dependencies>

構(gòu)建Flink流處理環(huán)境

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

自定義source

每秒生成一行文本

DataStreamSource<String> wordLineDS = env.addSource(new RichSourceFunction<String>() {
      private boolean isCanal = false;
      private String[] words = {
          "important oracle jdk license update",
          "the oracle jdk license has changed for releases starting april 16 2019",
          "the new oracle technology network license agreement for oracle java se is substantially different from prior oracle jdk licenses the new license permits certain uses such as ",
          "personal use and development use at no cost but other uses authorized under prior oracle jdk licenses may no longer be available please review the terms carefully before ",
          "downloading and using this product an faq is available here ",
          "commercial license and support is available with a low cost java se subscription",
          "oracle also provides the latest openjdk release under the open source gpl license at jdk java net"
      };

      @Override
      public void run(SourceContext<String> ctx) throws Exception {
        // 每秒發(fā)送一行文本
        while (!isCanal) {
          int randomIndex = RandomUtils.nextInt(0, words.length);
          ctx.collect(words[randomIndex]);
          Thread.sleep(1000);
        }
      }

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

單詞計(jì)算

// 3. 單詞統(tǒng)計(jì)
    // 3.1 將文本行切分成一個(gè)個(gè)的單詞
    SingleOutputStreamOperator<String> wordsDS = wordLineDS.flatMap((String line, Collector<String> ctx) -> {
      // 切分單詞
      Arrays.stream(line.split(" ")).forEach(word -> {
        ctx.collect(word);
      });
    }).returns(Types.STRING);

    //3.2 將單詞轉(zhuǎn)換為一個(gè)個(gè)的元組
    SingleOutputStreamOperator<Tuple2<String, Integer>> tupleDS = wordsDS
        .map(word -> Tuple2.of(word, 1))
        .returns(Types.TUPLE(Types.STRING, Types.INT));

    // 3.3 按照單詞進(jìn)行分組
    KeyedStream<Tuple2<String, Integer>, String> keyedDS = tupleDS.keyBy(tuple -> tuple.f0);

    // 3.4 對(duì)每組單詞數(shù)量進(jìn)行累加
    SingleOutputStreamOperator<Tuple2<String, Integer>> resultDS = keyedDS
        .timeWindow(Time.seconds(3))
        .reduce((t1, t2) -> Tuple2.of(t1.f0, t1.f1 + t2.f1));

    resultDS.print();

參考代碼

public class WordCount {
  public static void main(String[] args) throws Exception {
    // 1. 構(gòu)建Flink流式初始化環(huán)境
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

    // 2. 自定義source - 每秒發(fā)送一行文本
    DataStreamSource<String> wordLineDS = env.addSource(new RichSourceFunction<String>() {
      private boolean isCanal = false;
      private String[] words = {
          "important oracle jdk license update",
          "the oracle jdk license has changed for releases starting april 16 2019",
          "the new oracle technology network license agreement for oracle java se is substantially different from prior oracle jdk licenses the new license permits certain uses such as ",
          "personal use and development use at no cost but other uses authorized under prior oracle jdk licenses may no longer be available please review the terms carefully before ",
          "downloading and using this product an faq is available here ",
          "commercial license and support is available with a low cost java se subscription",
          "oracle also provides the latest openjdk release under the open source gpl license at jdk java net"
      };

      @Override
      public void run(SourceContext<String> ctx) throws Exception {
        // 每秒發(fā)送一行文本
        while (!isCanal) {
          int randomIndex = RandomUtils.nextInt(0, words.length);
          ctx.collect(words[randomIndex]);
          Thread.sleep(1000);
        }
      }

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

    // 3. 單詞統(tǒng)計(jì)
    // 3.1 將文本行切分成一個(gè)個(gè)的單詞
    SingleOutputStreamOperator<String> wordsDS = wordLineDS.flatMap((String line, Collector<String> ctx) -> {
      // 切分單詞
      Arrays.stream(line.split(" ")).forEach(word -> {
        ctx.collect(word);
      });
    }).returns(Types.STRING);

    //3.2 將單詞轉(zhuǎn)換為一個(gè)個(gè)的元組
    SingleOutputStreamOperator<Tuple2<String, Integer>> tupleDS = wordsDS
        .map(word -> Tuple2.of(word, 1))
        .returns(Types.TUPLE(Types.STRING, Types.INT));

    // 3.3 按照單詞進(jìn)行分組
    KeyedStream<Tuple2<String, Integer>, String> keyedDS = tupleDS.keyBy(tuple -> tuple.f0);

    // 3.4 對(duì)每組單詞數(shù)量進(jìn)行累加
    SingleOutputStreamOperator<Tuple2<String, Integer>> resultDS = keyedDS
        .timeWindow(Time.seconds(3))
        .reduce((t1, t2) -> Tuple2.of(t1.f0, t1.f1 + t2.f1));

    resultDS.print();

    env.execute("app");
  }
}

Flink對(duì)Java Lambda表達(dá)式支持情況

Flink支持Java API所有操作符使用Lambda表達(dá)式。但是,但Lambda表達(dá)式使用Java泛型時(shí),就需要聲明類型信息。

我們來(lái)看下上述的這段代碼:

SingleOutputStreamOperator<String> wordsDS = wordLineDS.flatMap((String line, Collector<String> ctx) -> {
      // 切分單詞
      Arrays.stream(line.split(" ")).forEach(word -> {
        ctx.collect(word);
      });
    }).returns(Types.STRING);

之所以這里將所有的類型信息,因?yàn)镕link無(wú)法正確自動(dòng)推斷出來(lái)Collector中帶的泛型。我們來(lái)看一下FlatMapFuntion的源代碼

@Public
@FunctionalInterface
public interface FlatMapFunction<T, O> extends Function, Serializable {

  /**
  * The core method of the FlatMapFunction. Takes an element from the input data set and transforms
  * it into zero, one, or more elements.
  *
  * @param value The input value.
  * @param out The collector for returning result values.
  *
  * @throws Exception This method may throw exceptions. Throwing an exception will cause the operation
  *          to fail and may trigger recovery.
  */
  void flatMap(T value, Collector<O> out) throws Exception;
}

我們發(fā)現(xiàn) flatMap的第二個(gè)參數(shù)是Collector<O>,是一個(gè)帶參數(shù)的泛型。Java編譯器編譯該代碼時(shí)會(huì)進(jìn)行參數(shù)類型擦除,所以Java編譯器會(huì)變成成:

void flatMap(T value, Collector out)

這種情況,F(xiàn)link將無(wú)法自動(dòng)推斷類型信息。如果我們沒(méi)有顯示地提供類型信息,將會(huì)出現(xiàn)以下錯(cuò)誤:

org.apache.flink.api.common.functions.InvalidTypesException: The generic type parameters of 'Collector' are missing.
  In many cases lambda methods don't provide enough information for automatic type extraction when Java generics are involved.
  An easy workaround is to use an (anonymous) class instead that implements the 'org.apache.flink.api.common.functions.FlatMapFunction' interface.
  Otherwise the type has to be specified explicitly using type information.

這種情況下,必須要顯示指定類型信息,否則輸出將返回值視為Object類型,這將導(dǎo)致Flink無(wú)法正確序列化。

所以,我們需要顯示地指定Lambda表達(dá)式的參數(shù)類型信息,并通過(guò)returns方法顯示指定輸出的類型信息

我們?cè)倏匆欢未a:

SingleOutputStreamOperator<Tuple2<String, Integer>> tupleDS = wordsDS
        .map(word -> Tuple2.of(word, 1))
        .returns(Types.TUPLE(Types.STRING, Types.INT));

為什么map后面也需要指定類型呢?

因?yàn)榇颂巑ap返回的是Tuple2類型,Tuple2是帶有泛型參數(shù),在編譯的時(shí)候同樣會(huì)被查出泛型參數(shù)信息,導(dǎo)致Flink無(wú)法正確推斷。

更多關(guān)于對(duì)Java Lambda表達(dá)式的支持請(qǐng)參考官網(wǎng):https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/java_lambdas.html

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • spring-boot-autoconfigure模塊用法詳解

    spring-boot-autoconfigure模塊用法詳解

    autoconfigure就是自動(dòng)配置的意思,spring-boot通過(guò)spring-boot-autoconfigure體現(xiàn)了"約定優(yōu)于配置"這一設(shè)計(jì)原則,而spring-boot-autoconfigure主要用到了spring.factories和幾個(gè)常用的注解條件來(lái)實(shí)現(xiàn)自動(dòng)配置,思路很清晰也很簡(jiǎn)單,感興趣的朋友跟隨小編一起看看吧
    2022-11-11
  • 使用Java如何對(duì)復(fù)雜的數(shù)據(jù)類型排序和比大小

    使用Java如何對(duì)復(fù)雜的數(shù)據(jù)類型排序和比大小

    我相信大家在第一次接觸算法的時(shí)候,最先接觸的肯定也是從排序算法開始的,下面這篇文章主要給大家介紹了關(guān)于使用Java如何對(duì)復(fù)雜的數(shù)據(jù)類型排序和比大小的相關(guān)資料,需要的朋友可以參考下
    2023-12-12
  • SpringBoot項(xiàng)目配置文件注釋亂碼的問(wèn)題解決方案

    SpringBoot項(xiàng)目配置文件注釋亂碼的問(wèn)題解決方案

    這篇文章主要介紹了SpringBoot 項(xiàng)目配置文件注釋亂碼的問(wèn)題解決方案,文中通過(guò)圖文結(jié)合的方式給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-07-07
  • Spring6當(dāng)中獲取Bean的四種方式小結(jié)

    Spring6當(dāng)中獲取Bean的四種方式小結(jié)

    Spring 為Bean 的獲取提供了多種方式,通常包括4種方式,(也就是說(shuō)在Spring中為Bean對(duì)象的創(chuàng)建準(zhǔn)備了多種方案,目的是:更加靈活),本文將通過(guò)代碼示例詳細(xì)的給大家介紹了一下這四種方式,需要的朋友可以參考下
    2024-04-04
  • 解讀.idea文件的使用及說(shuō)明

    解讀.idea文件的使用及說(shuō)明

    文章介紹了IntelliJ IDEA項(xiàng)目中的.idea文件夾及其作用,包括編譯配置、工作空間配置、項(xiàng)目標(biāo)識(shí)文件、編碼配置、jar包信息以及插件配置等,同時(shí),文章提醒在版本控制時(shí)應(yīng)排除.idea文件夾,以避免版本沖突
    2025-01-01
  • springboot中引入日志文件生成的配置詳解

    springboot中引入日志文件生成的配置詳解

    本文主要介紹了springboot中引入日志文件生成的配置詳解,包括日志級(jí)別的設(shè)置、日志格式的配置以及日志輸出的位置等,從而幫助開發(fā)者更好地進(jìn)行開發(fā)與調(diào)試
    2023-10-10
  • 淺談JSP與Servlet傳值及對(duì)比(總結(jié))

    淺談JSP與Servlet傳值及對(duì)比(總結(jié))

    下面小編就為大家?guī)?lái)一篇淺談JSP與Servlet傳值及對(duì)比(總結(jié))。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-05-05
  • idea如何添加工具到導(dǎo)航欄

    idea如何添加工具到導(dǎo)航欄

    文章介紹了如何在IntelliJ IDEA中將工具欄添加到導(dǎo)航欄,并具體步驟如下:勾選Toolbar,進(jìn)入File下的Settings,選擇MainToolbar,添加Action并選擇Settings和ProjectStructure,最后點(diǎn)擊OK將其添加到工具欄
    2025-01-01
  • Java編程使用UDP建立群聊系統(tǒng)代碼實(shí)例

    Java編程使用UDP建立群聊系統(tǒng)代碼實(shí)例

    這篇文章主要介紹了Java編程使用UDP建立群聊系統(tǒng)代碼實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2018-01-01
  • 帶你入門Java的方法

    帶你入門Java的方法

    這篇文章主要介紹了java基礎(chǔ)之方法詳解,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-07-07

最新評(píng)論

宽城| 鄂伦春自治旗| 嘉峪关市| 锡林郭勒盟| 上虞市| 澄城县| 塔河县| 瓦房店市| 开封市| 公安县| 朝阳区| 巴彦县| 平罗县| 台中县| 弥勒县| 左云县| 忻城县| 嘉峪关市| 辉县市| 巴林右旗| 灵丘县| 浙江省| 祁阳县| 灵寿县| 芮城县| 辽源市| 昌图县| 涟源市| 威海市| 荆门市| 哈密市| 新晃| 绥棱县| 威宁| 堆龙德庆县| 印江| 泾阳县| 新丰县| 扬州市| 乃东县| 涡阳县|