大数据实验 实验七:Flink低级编程实践

铁佛  金牌会员 | 2024-6-19 06:46:51 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 919|帖子 919|积分 2757

大数据实验 实验七:Flink低级编程实践

实验环境:Windows 10 Oracle VM VirtualBox
虚拟机:cnetos 7
Hadoop 3.3
实验内容与完成情况:

1. 利用IntelliJ IDEA工具开发WordCount程序

在Linux操作体系中安装IntelliJ IDEA,然后利用IntelliJ IDEA工具开发WordCount程序,并打包成JAR包,提交到Flink中运行。

下载flink安装包后解压


启动flink,


程序原码

WordCountData
  1. package WordCount;
  2. import org.apache.flink.api.java.DataSet;
  3. import org.apache.flink.api.java.ExecutionEnvironment;
  4. public class WordCountData {
  5.     public static final String[] WORDS = new String[]{"To be, or not to be,--that is the question:--", "Whether \'tis nobler in the mind to suffer", "The slings and arrows of outrageous fortune", "Or to take arms against a sea of troubles,", "And by opposing end them?--To die,--to sleep,--", "No more; and by a sleep to say we end", "The heartache, and the thousand natural shocks", "That flesh is heir to,--\'tis a consummation", "Devoutly to be wish\'d. To die,--to sleep;--", "To sleep! perchance to dream:--ay, there\'s the rub;", "For in that sleep of death what dreams may come,", "When we have shuffled off this mortal coil,", "Must give us pause: there\'s the respect", "That makes calamity of so long life;", "For who would bear the whips and scorns of time,", "The oppressor\'s wrong, the proud man\'s contumely,", "The pangs of despis\'d love, the law\'s delay,", "The insolence of office, and the spurns", "That patient merit of the unworthy takes,", "When he himself might his quietus make", "With a bare bodkin? who would these fardels bear,", "To grunt and sweat under a weary life,", "But that the dread of something after death,--", "The undiscover\'d country, from whose bourn", "No traveller returns,--puzzles the will,", "And makes us rather bear those ills we have", "Than fly to others that we know not of?", "Thus conscience does make cowards of us all;", "And thus the native hue of resolution", "Is sicklied o\'er with the pale cast of thought;", "And enterprises of great pith and moment,", "With this regard, their currents turn awry,", "And lose the name of action.--Soft you now!", "The fair Ophelia!--Nymph, in thy orisons", "Be all my sins remember\'d."};
  6.     public WordCountData() {
  7.     }
  8.     public static DataSet<String> getDefaultTextLineDataset(ExecutionEnvironment env) {
  9.         return env.fromElements(WORDS);
  10.     }
  11. }
复制代码
WordCountTokenizer

  1. package WordCount;
  2. import org.apache.flink.api.common.functions.FlatMapFunction;
  3. import org.apache.flink.api.java.tuple.Tuple2;
  4. import org.apache.flink.util.Collector;
  5. public class WordCountTokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> {
  6.     public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
  7.         String[] tokens = value.toLowerCase().split("\\W+");
  8.         int len = tokens.length;
  9.         for (int i = 0; i < len; i++) {
  10.             String tmp = tokens[i];
  11.             if (tmp.length() > 0) {
  12.                 out.collect(new Tuple2<String, Integer>(tmp, Integer.valueOf(1)));
  13.             }
  14.         }
  15.     }
  16. }
复制代码
WordCount

  1. package WordCount;
  2. import org.apache.flink.api.java.DataSet;
  3. import org.apache.flink.api.java.ExecutionEnvironment;
  4. import org.apache.flink.api.java.operators.AggregateOperator;
  5. import org.apache.flink.api.java.utils.ParameterTool;
  6. public class WordCount {
  7.     public WordCount() {
  8.     }
  9.     public static void main(String[] args) throws Exception {
  10.         ParameterTool params = ParameterTool.fromArgs(args);
  11.         ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
  12.         env.getConfig().setGlobalJobParameters(params);
  13.         Object text;
  14. //如果没有指定输入路径,则默认使用WordCountData中提供的数据
  15.         if (params.has("input")) {
  16.             text = env.readTextFile(params.get("input"));
  17.         } else {
  18.             System.out.println("Executing WordCount example with default input data set.");
  19.             System.out.println("Use -- input to specify file input.");
  20.             text = WordCountData.getDefaultTextLineDataset(env);
  21.         }
  22.         AggregateOperator counts = ((DataSet) text).flatMap(new WordCountTokenizer()).groupBy(new int[]{0}).sum(1);
  23. //如果没有指定输出,则默认打印到控制台
  24.         if (params.has("output")) {
  25.             counts.writeAsCsv(params.get("output"), "\n", " ");
  26.             env.execute();
  27.         } else {
  28.             System.out.println("Printing result to stdout. Use --output to specify output path.");
  29.             counts.print();
  30.         }
  31.     }
  32. }
复制代码
运行成功

2. 数据流词频统计

利用Linux操作体系自带的NC程序模仿天生数据流,不断产生单词并发送出去。编写Fink程序对NC程序发来的单词举行实时处理,盘算词频,并输出词频统计效果。要求首先在IntelliJ IDEA中开发和调试程序,然后打包成JAR包部署到Flink中运行。
编写程序
  1. package WordCount;
  2. import org.apache.flink.api.common.functions.FlatMapFunction;
  3. import org.apache.flink.api.java.utils.ParameterTool;
  4. import org.apache.flink.streaming.api.datastream.DataStream;
  5. import org.apache.flink.streaming.api.datastream.DataStreamSource;
  6. import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
  7. import org.apache.flink.streaming.api.windowing.time.Time;
  8. import org.apache.flink.util.Collector;
  9. public class WordCount {
  10.     public static void main(String[] args) throws Exception {
  11. //定义socket的端口号
  12.         int port;
  13.         try {
  14.             ParameterTool parameterTool = ParameterTool.fromArgs(args);
  15.             port = parameterTool.getInt("port");
  16.         } catch (Exception e) {
  17.             System.err.println("指定port参数,默认值为9000");
  18.             port = 9000;
  19.         }
  20. //获取运行环境
  21.         StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  22. //连接socket获取输入的数据
  23.         DataStreamSource<String> text = env.socketTextStream("127.0.0.1", port, "\n");
  24. //计算数据
  25.         DataStream<WordWithCount> windowCount = text.flatMap(new FlatMapFunction<String, WordWithCount>() {
  26.                     public void flatMap(String value, Collector<WordWithCount> out) throws Exception {
  27.                         String[] splits = value.split("\\s");
  28.                         for (String word : splits) {
  29.                             out.collect(new WordWithCount(word, 1L));
  30.                         }
  31.                     }
  32.                 })//打平操作,把每行的单词转为<word,count>类型的数据
  33.                 .keyBy("word")//针对相同的word数据进行分组
  34.                 .timeWindow(Time.seconds(2), Time.seconds(1))//指定计算数据的窗口大小和滑动窗口大小
  35.                 .sum("count");
  36. //把数据打印到控制台
  37.         windowCount.print()
  38.                 .setParallelism(1);//使用一个并行度
  39. //注意:因为flink是懒加载的,所以必须调用execute方法,上面的代码才会执行
  40.         env.execute("streaming word count");
  41.     }
  42.     /**
  43.      * 主要为了存储单词以及单词出现的次数
  44.      */
  45.     public static class WordWithCount {
  46.         public String word;
  47.         public long count;
  48.         public WordWithCount() {
  49.         }
  50.         public WordWithCount(String word, long count) {
  51.             this.word = word;
  52.             this.count = count;
  53.         }
  54.         @Override
  55.         public String toString() {
  56.             return "WordWithCount{" +
  57.                     "word='" + word + '\'' +
  58.                     ", count=" + count +
  59.                     '}';
  60.         }
  61.     }
复制代码
运行包

向nc中输入数据

读取到数据

出现的题目

题目一


Flink进程已经启动但是用浏览器访问8081失败
题目二


运行打包的程序出现报错
题目三

利用linux自带的nc出现题目

没有找到下令
题目四


运行时出现找不到包的错误
题目五


运行时报错,缺少方法
题目六

在9000端口传入数据后,flink监听会报错
解决方案

题目一


配置的地址是localhost
将文档中的数据改为192.168.118.128:8081
题目解决

题目二

在maven项目中添加
  1. <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
  2.     <resource>reference.conf</resource>
  3. </transformer>
复制代码
题目解决
题目三

yum install -y nc 安装nc

题目解决
题目四

在打包时将flink/lib下的文件也打入包中
题目解决
题目五



利用flink的依赖包时必要严格保证包的版本号与启动的flink完全同等
不然就会出现缺少方法的报错

启动成功题目解决
题目六


在利用老版的窗口时,未指定时间语义,导致报错.
必要设置时间语义

题目解决


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

铁佛

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表