flink 有狀態(stateful)的計算
import org.apache.flink.api.common.functions.RichFlatMapFunction import org.apache.flink.api.common.state.ValueState import org.apache.flink.util.Collector import org.apache.flink.configuration.Configuration import org.apache.flink.api.common.state.ValueStateDescriptor import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment class CountWindowAverage extends RichFlatMapFunction[(Long, Double), (Long, Double)] { private var sum: ValueState[(Long, Double)] = _ override def flatMap(input: (Long, Double), out: Collector[(Long, Double)]): Unit = { // access the state value val tmpCurrentSum = sum.value // If it hasn't been used before, it will be null val currentSum = if (tmpCurrentSum != null) { tmpCurrentSum } else { (0L, 0d) } // update the count val newSum = (currentSum._1 + 1, currentSum._2 + input._2) // update the state sum.update(newSum) // if the count reaches 2, emit the average and clear the state if (newSum._1 >= 2) { out.collect((input._1, newSum._2 / newSum._1)) //將狀態清除 //sum.clear() } } override def open(parameters: Configuration): Unit = { sum = getRuntimeContext.getState( new ValueStateDescriptor[(Long, Double)]("average", classOf[(Long, Double)]) ) } } import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment import org.apache.flink.api.scala._ object ECountWindowAverage { def main(args: Array[String]): Unit = { val env = StreamExecutionEnvironment.getExecutionEnvironment env.fromCollection(List( (1L, 3d), (1L, 5d), (1L, 7d), (1L, 4d), (1L, 2d) )).keyBy(_._1) .flatMap(new CountWindowAverage()) .print() /*.keyBy(_._1) .flatMap(new CountWindowAverage()) .print()*/ // the printed output will be (1,4) and (1,5) env.execute("ExampleManagedState") } }
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31506529/viewspace-2645402/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 有狀態Stateful,富含資料的CI/CD怎麼做?
- 如何證明CRM WebClient UI上的應用是有狀態(Stateful)的WebclientUI
- docker筆記28-stateful(有狀態應用副本集)控制器Docker筆記
- Flink 2.0 狀態存算分離改造實踐
- 深入理解Flink中的狀態
- Flink的狀態程式設計和容錯機制(四)程式設計
- 系統設計架構:有狀態與無狀態架構
- 扒一扒React計算狀態的原理React
- 有狀態和無狀態的區別
- 【Flink入門修煉】2-2 Flink State 狀態
- SAP Fiori和WebClient UI的有狀態和無狀態行為設計原理WebclientUI
- 實時計算 Flink> 產品簡介——最新動態
- 架構設計(五):有狀態服務和無狀態服務架構
- 計算資料庫有多少工作是在最優狀態下進行的語句資料庫
- Spring Bean Scope 有狀態的Bean和無狀態的BeanSpringBean
- Flink狀態管理和容錯機制介紹
- flink學習(加餐)——job任務狀態變化
- Flink計算pv和uv的通用方法
- Apache Flink,流計算?不僅僅是流計算!Apache
- 關於有狀態和無狀態會話bean的解釋 (轉)會話Bean
- Flink 在有贊實時計算的實踐
- Flink處理函式實戰之一:深入瞭解ProcessFunction的狀態(Flink-1.10)函式Function
- 位運算-設計資料庫表的多選狀態欄位資料庫
- Flink實時計算topN熱榜
- 實時計算Flink——產品安全
- 實時計算Flink效能調優
- 用設計模式去掉沒必要的狀態變數 —— 狀態模式設計模式變數
- Flink CheckPoint狀態點恢復與savePoint機制對比剖析-Flink牛刀小試
- Flink 狀態管理與checkPoint資料容錯機制深入剖析-Flink牛刀小試
- 從Storm到Flink,有贊五年實時計算效率提升實踐ORM
- 最全的HTTP響應狀態碼列表:除了404,HTTP狀態碼還有啥?HTTP
- [原始碼分析]從"UDF不應有狀態" 切入來剖析Flink SQL程式碼生成 (修訂版)原始碼SQL
- 流計算框架 Flink 與 Storm 的效能對比框架ORM
- Flink實時計算pv、uv的幾種方法
- Flink流計算中SQL表的概念和原理SQL
- Flink不止於計算,存算一體才是未來
- 實時計算Flink——快速入門概述
- 設計模式-狀態模式設計模式