Flink------DataStream--wordcount

一个简单的单词计数程序。注解可以说是很详细了 。

public class SocketWordCount {

    public static void main(String[] args)throws Exception {
        // 获取执行环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 获取数据流,例子中是从指定端口的socket中获取用户输入的文本
        DataStream<String> text = env.socketTextStream("localhost", 9999);
        // transformation操作,对数据流实现算法
        DataStream<WordWithCount> windowCounts = text
                //将用户输入的文本流以非空白符的方式拆开来,得到单个的单词,存入命名为out的Collector中
                .flatMap(new SplitString())
                //将数据按照“word”分组,其实就是按照不同的单词分组。
                //这个word和下面的“count”都是WordWithCount内定义的字段。
                //这里也可以不用自定义WordWithCount,可以使用tuple。
                //当然,要是使用tuple的话,在new SplitString()中,collector.collect的就得是Tuple类型了。
                .keyBy("word")  
                //这个滚动窗口的计算,是每次计算5秒的数据(这个时间可以自己设置),
                //第一个5秒和第二个5秒的数据没有任何关系。
                //比如,第一个5秒,hello出现了10次,word出现了8次;第二个5秒,hello和word的出现次数会从0开始计算。
				//  .timeWindow(Time.seconds(5))
				//滑动窗口机制,每2秒计算一次最近5秒的数据
                .timeWindow(Time.seconds(5), Time.seconds(2))
                //可以直接使用这个算子,计算单词出现次数
                .sum("count"); 
                //也可以使用reduce计算,sum更简便一些。
//                .reduce(new ReduceFunction<WordWithCount>() {
//                    public WordWithCount reduce(WordWithCount a, WordWithCount b) {
//                        return new WordWithCount(a.word, a.count + b.count);
//                    }
//                });
        // 单线程执行该程序
        windowCounts.print().setParallelism(1);
		// windowCounts.writeAsText("/root/flink/output/wordcount.txt", WriteMode.NO_OVERWRITE).setParallelism(1);
        //提交执行
        env.execute();
    }

    public static class SplitString
            implements FlatMapFunction<String, WordWithCount> {
        private  static final long serialVersionUID=1L;
        @Override
        public void flatMap(String s, Collector<WordWithCount> collector) {
            for (String word : s.split(" ")) {
                collector.collect(new WordWithCount(word, 1));
            }
            ;
        }
    }
}

public class WordWithCount {
    //两个变量存储输入的单词及其数量
    public String word;
    public long count;

	//无参构造必须要有的
    public WordWithCount() {}   

    public WordWithCount(String word, long count) {
        this.word = word;
        this.count = count;
    }

    @Override
    public String toString() {
        return "[ " + word + " : " + count +" ]";
    }
}

感谢各位大佬前来。

Flink WordCountFlink 的一个经典示例,用于演示 Flink 流处理的基本功能。它是一个简单的单词计数程序,可以从输入文本中读取单词,并计算每个单词在文本中出现的次数。 以下是一个 Flink WordCount 的示例代码: ```java import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.source.FileSource; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.streaming.api.windowing.time.Time; public class WordCount { public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); // 设置执行环境 final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 设置数据源 DataStream<String> text; if (params.has("input")) { text = env.readTextFile(params.get("input")); } else { System.out.println("Executing WordCount example with default input data set."); System.out.println("Use --input to specify file input."); text = env.fromElements(WordCountData.WORDS); } // 转换数据流 DataStream<WordWithCount> counts = text.flatMap(new Tokenizer()) .keyBy("word") .timeWindow(Time.seconds(5)) .sum("count"); // 输出结果 if (params.has("output")) { counts.writeAsText(params.get("output")); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); counts.print(); } // 执行任务 env.execute("Streaming WordCount"); } // 单词拆分函数 public static final class Tokenizer implements FlatMapFunction<String, WordWithCount> { @Override public void flatMap(String value, Collector<WordWithCount> out) { String[] tokens = value.toLowerCase().split("\\W+"); for (String token : tokens) { if (token.length() > 0) { out.collect(new WordWithCount(token, 1L)); } } } } // 单词计数类 public static final class WordWithCount { public String word; public long count; public WordWithCount() {} public WordWithCount(String word, long count) { this.word = word; this.count = count; } @Override public String toString() { return word + " : " + count; } } } ``` 该程序使用 Flink 流处理 API 来读取输入文本、拆分单词、计数单词并输出结果。程序的具体执行流程如下: 1. 读取命令行参数或默认数据源。 2. 创建 Flink 执行环境。 3. 读取数据源。 4. 转换数据流,拆分单词并计数。 5. 输出结果到文件或标准输出。 6. 执行任务。 如果你想要运行 Flink WordCount 示例程序,可以按照以下步骤进行: 1. 下载 Flink 并解压。 2. 打开终端并进入 Flink 的安装目录。 3. 运行 `./bin/start-cluster.sh` 启动 Flink 集群。 4. 运行 `./bin/flink run examples/streaming/WordCount.jar --input /path/to/input/file --output /path/to/output/file`。 5. 等待程序执行完成,查看输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值