1、mapWithState
案例:是wordCount小程序,单词word持续增加,由5增加到100了,还会持续增加,因为用到了它的前置数据。必须checkPoint。
ssc.checkpoint("hdfs://linux-hadoop01.ibeifeng.com:8020/beifeng/spark/streaming/chkdir45254")
def mappingFunction(key: String, values: Option[Int], state: State[Long]): (String, Long) = { // 获取之前状态的值 val preStateValue = state.getOption().getOrElse(0L) // 计算出当前值 val currentStateValue = preStateValue + values.getOrElse(0) // 更新状态值 state.update(currentStateValue) // 返回结果 (key, currentStateValue) } val result = messages.flatMap(x => x.split(" ")). map(x => (x, 1)). reduceByKey((x, y) => { x + y }). mapWithState(StateSpec.function(mappingFunction _))//方法转函数
2、reduceByKeyAndWindow
有状态转换reduceByKeyAndWindow(),批处理时间是second(5),只计算窗口里面的数据,并不会累加。Second(15)表示窗口大小,second(10)表示滑动大小。
比如说有的需求是计算每小时的数据,就可以用这个
第一个参数是你想对窗口中的数据进行什么操作的函数,第二个是窗口函数,第三个是步长。