1. 程式人生 > >Flink處理函式實戰之四:視窗處理

Flink處理函式實戰之四:視窗處理

### 歡迎訪問我的GitHub [https://github.com/zq2599/blog_demos](https://github.com/zq2599/blog_demos) 內容:所有原創文章分類彙總及配套原始碼,涉及Java、Docker、Kubernetes、DevOPS等; ### Flink處理函式實戰系列連結 1. [深入瞭解ProcessFunction的狀態操作(Flink-1.10)](https://blog.csdn.net/boling_cavalry/article/details/106040312); 2. [ProcessFunction](https://xinchen.blog.csdn.net/article/details/106299035); 3. [KeyedProcessFunction類](https://xinchen.blog.csdn.net/article/details/106299167); 4. [ProcessAllWindowFunction(視窗處理)](https://xinchen.blog.csdn.net/article/details/106453229); 5. [CoProcessFunction(雙流處理)](https://xinchen.blog.csdn.net/article/details/109614001); ### 本篇概覽 本文是《Flink處理函式實戰》系列的第四篇,內容是學習以下兩個視窗相關的處理函式: 1. ProcessAllWindowFunction:處理每個視窗內的所有元素; 2. ProcessWindowFunction:處理指定key的每個視窗內的所有元素; ### 關於ProcessAllWindowFunction 1. ProcessAllWindowFunction和[《Flink處理函式實戰之二:ProcessFunction類》](https://xinchen.blog.csdn.net/article/details/106299035)中的ProcessFunction類相似,都是用來對上游過來的元素做處理,不過ProcessFunction是每個元素執行一次processElement方法,ProcessAllWindowFunction是每個視窗執行一次process方法(方法內可以遍歷該視窗內的所有元素); 2. 用類圖對比可以更形象的認識差別,下圖左側是ProcessFunction,右側是ProcessAllWindowFunction: ![在這裡插入圖片描述](https://img2020.cnblogs.com/other/485422/202011/485422-20201123090920212-180109452.png) ### 關於ProcessWindowFunction 1. ProcessWindowFunction和KeyedProcessFunction類似,都是處理分割槽的資料,不過KeyedProcessFunction是每個元素執行一次processElement方法,而ProcessWindowFunction是每個視窗執行一次process方法(方法內可以遍歷該key當前視窗內的所有元素); 2. 用類圖對比可以更形象的認識差別,下圖左側是KeyedProcessFunction,右側是ProcessWindowFunction: ![在這裡插入圖片描述](https://img2020.cnblogs.com/other/485422/202011/485422-20201123090920658-848383442.png) 3. 另外還一個差異:ProcessWindowFunction.process方法的入參就有分割槽的key值,而KeyedProcessFunction.processElement方法的入參沒有這個引數,而是需要Context.getCurrentKey()才能取到分割槽的key值; ### 注意事項 視窗處理函式的process方法,以ProcessAllWindowFunction為例,如下圖紅框所示,其入參可以遍歷當前視窗內的所有元素,這意味著當前視窗的所有元素都儲存在堆記憶體中,所以請在設計階段就嚴格控制視窗內元素的記憶體使用量,避免耗盡TaskManager節點的堆記憶體: ![在這裡插入圖片描述](https://img2020.cnblogs.com/other/485422/202011/485422-20201123090921343-435630790.png) 接下來通過實戰學習ProcessAllWindowFunction和ProcessWindowFunction; ### 版本資訊 1. 開發環境作業系統:MacBook Pro 13寸, macOS Catalina 10.15.4 2. 開發工具:IntelliJ IDEA 2019.3.2 (Ultimate Edition) 3. JDK:1.8.0_121 4. Maven:3.3.9 5. Flink:1.9.2 ### 原始碼下載 如果您不想寫程式碼,整個系列的原始碼可在GitHub下載到,地址和連結資訊如下表所示(https://github.com/zq2599/blog_demos): | 名稱 | 連結 | 備註| | :-------- | :----| :----| | 專案主頁| https://github.com/zq2599/blog_demos | 該專案在GitHub上的主頁 | | git倉庫地址(https)| https://github.com/zq2599/blog_demos.git | 該專案原始碼的倉庫地址,https協議 | | git倉庫地址(ssh)| [email protected]:zq2599/blog_demos.git | 該專案原始碼的倉庫地址,ssh協議 | 這個git專案中有多個資料夾,本章的應用在flinkstudy資料夾下,如下圖紅框所示: ![在這裡插入圖片描述](https://img2020.cnblogs.com/other/485422/202011/485422-20201123090921630-73134579.png) ### 如何實戰ProcessAllWindowFunction 接下來通過以下方式驗證ProcessAllWindowFunction功能: 1. 每隔1秒發出一