当前位置:   article > 正文

Flink安装及使用

flink安装及使用

本地部署

安装

  1. 官网安装Flink,并解压到/usr/local/flink

      1. sudo tar -zxf flink-1.6.2-bin-hadoop27-scala_2.11.tgz -C /usr/local
      2. cd /usr/local
    • 54388226982

  2. 修改文件名字,并设置权限

      1. sudo mv ./flink-*/ ./flink
      2. sudo chown -R hadoop:hadoop ./flink

修改配置文件

  • Flink对于本地模式是开箱即用的,如果要修改Java运行环境,可修改conf/flink-conf.yaml中的env.java.home,设置为本地java的绝对路径

添加环境变量

  1. vim ~/.bashrc
  2. export FLINK_HOME=/usr/local/flink
  3. export PATH=$FLINK_HOME/bin:$PATH

54388242695

启动Flink

start-cluster.sh
  • 可以通过观察logs目录下的日志来检测系统是否正在运行了
tail log/flink--jobmanager-.log

54388315301

54388290147

可以发现flink已经正常启动

运行示例

使用Maven创建Flink项目,在pom.xml中添加以下依赖:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.apache.flink</groupId>
  4. <artifactId>flink-java</artifactId>
  5. <version>1.6.2</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.flink</groupId>
  9. <artifactId>flink-streaming-java_2.11</artifactId>
  10. <version>1.6.2</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.apache.flink</groupId>
  14. <artifactId>flink-clients_2.11</artifactId>
  15. <version>1.6.2</version>
  16. </dependency>
  17. </dependencies>

批处理运行WordCount

官方示例

可以直接在/usr/local/flink/examples/batch中运行WordCount程序,并且这里还有更多示例:

54388437325

运行:

flink run WordCount.jar 

54388443638

代码

WordCountData

提供原始数据

  1. import org.apache.flink.api.java.DataSet;
  2. import org.apache.flink.api.java.ExecutionEnvironment;
  3. public class WordCountData {
  4. 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."};
  5. public WordCountData() {
  6. }
  7. public static DataSet<String> getDefaultTextLineDataset(ExecutionEnvironment env){
  8. return env.fromElements(WORDS);
  9. }
  10. }

WordCountTokenizer

切分句子

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

首先打包成JAR包,这里需要使用-c指定main函数:

flink run -c WordCount WordCount.jar

流处理运行WordCount

官方示例

可以直接在/usr/local/flink/examples/streaming中运行WordCount程序,并且这里还有更多示例:

54388669798

代码

SocketWindowWordCount

  1. import org.apache.flink.api.common.functions.FlatMapFunction;
  2. import org.apache.flink.api.java.utils.ParameterTool;
  3. import org.apache.flink.streaming.api.datastream.DataStream;
  4. import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
  5. import java.sql.Time;
  6. import java.util.stream.Collector;
  7. public class SocketWindowWordCount {
  8. public static void main(String[] args) throws Exception {
  9. // the port to connect to
  10. final int port;
  11. try {
  12. final ParameterTool params = ParameterTool.fromArgs(args);
  13. port = params.getInt("port");
  14. } catch (Exception e) {
  15. System.err.println("No port specified. Please run 'SocketWindowWordCount --port <port>'");
  16. return;
  17. }
  18. // get the execution environment
  19. final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  20. // get input data by connecting to the socket
  21. DataStream<String> text = env.socketTextStream("localhost", port, "\n");
  22. // parse the data, group it, window it, and aggregate the counts
  23. DataStream<WordWithCount> windowCounts = text
  24. .flatMap(new FlatMapFunction<String, WordWithCount>() {
  25. @Override
  26. public void flatMap(String value, Collector<WordWithCount> out) {
  27. for (String word : value.split("\\s")) {
  28. out.collect(new WordWithCount(word, 1L));
  29. }
  30. }
  31. })
  32. .keyBy("word")
  33. .timeWindow(Time.seconds(5), Time.seconds(1))
  34. .reduce(new ReduceFunction<WordWithCount>() {
  35. @Override
  36. public WordWithCount reduce(WordWithCount a, WordWithCount b) {
  37. return new WordWithCount(a.word, a.count + b.count);
  38. }
  39. });
  40. // print the results with a single thread, rather than in parallel
  41. windowCounts.print().setParallelism(1);
  42. env.execute("Socket Window WordCount");
  43. }
  44. // Data type for words with count
  45. public static class WordWithCount {
  46. public String word;
  47. public long count;
  48. public WordWithCount() {}
  49. public WordWithCount(String word, long count) {
  50. this.word = word;
  51. this.count = count;
  52. }
  53. @Override
  54. public String toString() {
  55. return word + " : " + count;
  56. }
  57. }
  58. }

首先打包成JAR包,然后启动netcat

nc -l 9000

将终端启动netcat作为输入流:

提交Jar包:

flink run -c SocketWindowWordCount WordCountSteaming.jar --port 9000

这样终端会一直等待netcat的输入流

54388822906

在netcat中输入字符流:

54388825265

可以在WebUI中查看运行结果:

54388897680



作者:zealscott
链接:https://www.jianshu.com/p/bbaa8d72cfcf/
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/764729
推荐阅读
相关标签
  

闽ICP备14008679号