新建maven程序
pom.xml依賴如下:
然后新建一個TestSocketWindowWordCount類具體代碼如下
然后啟動flink集群->新建一個監聽:nc -lk 6666
然后啟動TestSocketWindowWordCount類
在linux監聽頁面輸入代碼
觀察在idea控制臺就有統計的輸出
-------pom.xml開始-----------
-------pom.xml結束-----------
-------TestSocketWindowWordCount開始------------------
package com.gyb;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
創新互聯公司服務項目包括石柱土家族網站建設、石柱土家族網站制作、石柱土家族網頁制作以及石柱土家族網絡營銷策劃等。多年來,我們專注于互聯網行業,利用自身積累的技術優勢、行業經驗、深度合作伙伴關系等,向廣大中小型企業、政府機構等提供互聯網行業的解決方案,石柱土家族網站推廣取得了明顯的社會效益與經濟效益。目前,我們服務的客戶以成都為中心已經輻射到石柱土家族省份的部分城市,未來相信會繼續擴大服務區域并繼續獲得客戶的支持與信任!
import javax.xml.soap.Text;
public class TestSocketWindowWordCount {
public static void main(String args[]) {
String hostname = "192.168.198.130";
int port = 6666;
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream text = env.socketTextStream(hostname, port, "\n");//獲取執行環境
SingleOutputStreamOperator windowCounts = text
.flatMap(new FlatMapFunction
br/>@Override
out) {
for (String word : value.split("\s")) {
out.collect(new SocketWindowWordCount.WordWithCount(word, 1L));
}
}
})
.keyBy("word")
.timeWindow(Time.seconds(5), Time.seconds(5))
.reduce(new ReduceFunction
br/>@Override
return new SocketWindowWordCount.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");
try {
env.execute("Socket Window WordCount");
} catch (Exception e) {
e.printStackTrace();
}
}
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;
}
}
}
-------TestSocketWindowWordCount結束------------------