一、Linux上部署Flink
1.先在服务器上安装jdk1.8
2.下载Flink
wget https://archive.apache.org/dist/flink/flink-1.12.1/flink-1.12.1-bin-scala_2.11.tgz
3.解压Flink并进入到目录
tar -xvf flink-1.12.1-bin-scala_2.11.tgz
cd /usr/local/src/flink-1.12.1
4.启动Flink
./bin/start-cluster.bat
通过 http://localhost:8081 访问 Flink 的 web 页面,该站点用于查看运行环境和资源、提交和监控 Flink 作业。
二、在idea上创建Flink的工程
1.在 IDEA 中创建 Flink 应用的模板工程
在如上的页面点击 “Add Archetype…”,然后再弹出的对话框填写如下内容
2.创建测试类
3.将官网的WordCount例子的代码拷贝到自己的项目中
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
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.windowing.time.Time;
import org.apache.flink.util.Collector;
public class FirstCase {
public static void main(String[] args) throws Exception {
// the port to connect to
final int port = 8090;
// get the execution environment
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// get input data by connecting to the socket
DataStream<String> text = env.socketTextStream("192.168.109.138", port, "\n");
// parse the data, group it, window it, and aggregate the counts
DataStream<WordWithCount> windowCounts = text
.flatMap(new FlatMapFunction<String, WordWithCount>() {
@Override
public void flatMap(String value, Collector<WordWithCount> out) {
for (String word : value.split("\\s")) {
out.collect(new WordWithCount(word, 1L));
}
}
})
.keyBy("word")
.timeWindow(Time.seconds(5), Time.seconds(1))
.reduce(new ReduceFunction<WordWithCount>() {
@Override
public WordWithCount reduce(WordWithCount a, WordWithCount b) {
return new WordWithCount(a.word, a.count + b.count);
}
});
// print the results with a single thread, rather than in parallel
windowCounts.print().setParallelism(1);
env.execute("Socket Window WordCount");
}
// Data type for words with count
public static 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;
}
}
}
4.启动 netcat 用于发数据
安装nc命令
yum install -y nc
启动 netcat 用于发数据
为什么控制台输出5次a,因为代码中的这句
.timeWindow(Time.seconds(5), Time.seconds(1))
定义了一个滑动窗口,窗口大小为5秒,每1秒滑动一次
三、遇到的问题
问题:java项目启动的时候报错
解决方案:点击编辑配置
"Include dependencies with “Provided” scope"选择该项
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。