UpdateStateByKey操作

官网原话:

updateStateByKey操作允许您在使用新信息不断更新时保持任意状态。要使用它,您必须执行两个步骤。

  1. 定义状态 - 状态可以是任意数据类型。
  2. 定义状态更新功能 - 使用函数指定如何使用先前状态和输入流中的新值更新状态。

在每个批处理中,Spark都会对所有现有key应用状态更新功能,无论它们是否在批处理中都有新数据。如果更新函数返回,None则将删除key-valu

 

/**
   * Return a new "state" DStream where the state for each key is updated by applying
   * the given function on the previous state of the key and the new values of each key.
   * Hash partitioning is used to generate the RDDs with Spark's default number of partitions.
   * @param updateFunc State update function. If `this` function returns None, then
   *                   corresponding state key-value pair will be eliminated.
   * @tparam S State type
   */
  def updateStateByKey[S: ClassTag](
      updateFunc: (Seq[V], Option[S]) => Option[S]
    ): DStream[(K, S)] = ssc.withScope {
    updateStateByKey(updateFunc, defaultPartitioner())
  }

计算需要Partitioner。因为Hash高效率且不做排序,所以默认Partitioner是HashPartitoner。

源码中发现有七种重载函数,自行翻阅。github源码

package com.ruozedata.G5
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.{HashPartitioner, SparkConf, SparkContext}
import org.apache.log4j.Level
import org.apache.log4j.Logger
object updateStateByKey_test {
  Logger.getLogger("org.apache.spark").setLevel(Level.ERROR)

  val updateFunc = (iter: Iterator[(String, Seq[Int], Option[Int])]) => {
    //iter.flatMap(k=>Some(k._2.sum + k._3.getOrElse(0)).map(x=>(k._1,x)))
    //iter.map{case(x,y,z)=>Some(y.sum + z.getOrElse(0)).map(m=>(x, m))}
    //iter.map(k => (k._1, k._2.sum + k._3.getOrElse(0)))
    iter.map{ case(word, current_count, history_count) => (word, current_count.sum + history_count.getOrElse(0)) }
  }

  def main(args: Array[String]) {
   // LoggerLevels.setStreamingLogLevels()
    //StreamingContext
    val conf = new SparkConf().setAppName("test_update").setMaster("local[2]")
    val sc = new SparkContext(conf)
    //updateStateByKey必须设置setCheckpointDir
    sc.setCheckpointDir("Z://check")
    val ssc = new StreamingContext(sc, Seconds(5))
    val ds = ssc.socketTextStream("hadoop001", 9998)
    val result = ds.flatMap(_.split(" ")).map((_, 1)).updateStateByKey(
      updateFunc, new HashPartitioner(sc.defaultParallelism), true)
    result.print()
    ssc.start()
    ssc.awaitTermination()
  }
}

例子如上所示。配合nc -lk 9999使用。

由于统计全局,所以需要checkpoint数据会占用较大的存储。而且效率也不高。数据很多的时候不建议使用updateStateByKey

import org.apache.spark.{SparkConf, SparkContext} import org.apache.spark.streaming.{Seconds, StreamingContext} import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream} object UpdateStateByKeyTest { //newValues表示当前批次汇总成的(K,V)中相同K的所有V //runningCount表示历史的所有相同key的value总和 def updateFunction(newValues: Seq[Int], runningCount: Option[Int]): Option[Int] = { val newCount = runningCount.getOrElse(0) + newValues.sum Some(newCount) } def main(args: Array[String]): Unit = { //1.创建StreamingContext,两个参数:1.SparkConf对象 2.批处理时间间隔 val ssc: StreamingContext = new StreamingContext(new SparkConf().setAppName("UpdateStateByKeyTest").setMaster("local[2]"), Seconds(5)) //2.设置日志级别 ssc.sparkContext.setLogLevel("WARN") //3.配置检查点目录,使用updateStateByKey()方法必须配置检查点目录 ssc.checkpoint("./") //4.连接socket服务,需要socket的地址,端口号,存储级别 val dstream: ReceiverInputDStream[String] = ssc.socketTextStream("192.168.92.131", 9999) //5.按空格切分每一行,并且将切分出来的单词出现的次数记录为1 val wordAndOne: DStream[(String, Int)] = dstream.flatMap(_.split(" ")).map(word => (word, 1)) //6.调用UpdateStateByKey操作,统计每个单词在全局中出现的次数 val result: DStream[(String,Int)] = wordAndOne.updateStateByKey(updateFunction) //7.打印输出结果 result.print() //8.开启流式计算 ssc.start() //9.用于保持程序一直运行,除非人为干预停止 ssc.awaitTermination() } } 上述代码出现:Exception in thread "main" org.apache.spark.SparkException: Task not serializable 报错,如何解决?
最新发布
05-28
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值