spark 共享变量

关于累计器, 广播变量, 参考:
http://blog.csdn.net/u013468917/article/details/70617085(累加器主要参考了这篇文章)
https://www.cnblogs.com/liuliliuli2017/p/6782687.html(广播变量)
http://blog.csdn.net/leen0304/article/details/78866353

对于多节点变量的共享, 我们可以依赖Redis混存数据库来实现。
Spark已经提供了两种特定的共享变量,来完成节点间变量的共享: 累加器和广播变量

累加器accumulator

继承于抽象类AccumulatorV2

// 输入两个类型参数 IN, OUT
abstract class AccumulatorV2[IN, OUT] extends Serializable {
  private[spark] var metadata: AccumulatorMetadata = _
  private[this] var atDriverSide = true

 //  注册累计器, 生成一个ID 和 Name
// countFailedValues对于失败的task是否计数, 默认false
 private[spark] def register(
      sc: SparkContext,
      name: Option[String] = None,
      countFailedValues: Boolean = false): Unit = {
    if (this.metadata != null) {
      throw new IllegalStateException("Cannot register an Accumulator twice.")
    }
    this.metadata = AccumulatorMetadata(AccumulatorContext.newId(), name, countFailedValues)
    AccumulatorContext.register(this)
    sc.cleaner.foreach(_.registerAccumulatorForCleanup(this))
  }
// 每个累计器只能和注册一次, 使用之前必须注册
final def isRegistered: Boolean =
    metadata != null && AccumulatorContext.get(metadata.id).isDefined

  private def assertMetadataNotNull(): Unit = {
    if (metadata == null) {
      throw new IllegalStateException("The metadata of this accumulator has not been assigned yet.")
    }
  }

final def id: Long = {
    assertMetadataNotNull()
    metadata.id
}

/**
   * Returns the name of this accumulator, can only be called after registration.
   */
 final def name: Option[String] = {
    assertMetadataNotNull()
    if (atDriverSide) {
metadata.name.orElse(AccumulatorContext.get(id).flatMap(_.metadata.name))
    } else {
      metadata.name
    }
  }

在继承类中必须需要提供实现的方法:
isZeros(): 累计器空的判断, 返回Boolean
copy(): 拷贝实现, 返回CollectionAccumulator
reset(): 重置
add():累计
merge(): 合并不同节点的累计器会使用
value: 累计器实际容器

/**
   * Returns if this accumulator is zero value or not. e.g. for a counter accumulator, 0 is zero
   * value; for a list accumulator, Nil is zero value.
   */
  def isZero: Boolean

/**
   * Creates a new copy of this accumulator.
   */
  def copy(): AccumulatorV2[IN, OUT]

 /** 清空
   * Resets this accumulator, which is zero value. i.e. call `isZero` must
   * return true.
   */
  def reset(): Unit

/** 累加的具体实现
   * Takes the inputs and accumulates.
   */
  def add(v: IN): Unit

/** 合并累计器到当前累计器
   * Merges another same-type accumulator into this one and update its state, i.e. this should be merge-in-place.
   */
  def merge(other: AccumulatorV2[IN, OUT]): Unit

/** 调用value的返回
   * Defines the current value of this accumulator
   */
  def value: OUT

Spark在SparkContext类中的提供了longAccumulator和doubleAccumulator, collectionAccumulator的累加器, 各有一个带name和不带name的重载接口, 具体实现代码在org.apache.spark.util

def collectionAccumulator[T]: CollectionAccumulator[T] = {
    val acc = new CollectionAccumulator[T]  // 定义累计器
    register(acc)  // 注册, name可选
    acc
  }

  /**
   * Create and register a `CollectionAccumulator`, which starts with empty list and accumulates
   * inputs by adding them into the list.
   */
  def collectionAccumulator[T](name: String): CollectionAccumulator[T] = {
    val acc = new CollectionAccumulator[T]
    register(acc, name)
    acc
  }

CollectionAccumulator 定义了一个list类型的累加器

class CollectionAccumulator[T] extends AccumulatorV2[T, java.util.List[T]] {
// 中间变量
  private val _list: java.util.List[T] = Collections.synchronizedList(new ArrayList[T]())
// 实现 isZero
  override def isZero: Boolean = _list.isEmpty
// 实现 copyAndReset, AccumulatorV2中提供了方法: 先copy, 再reset, 非必须
  override def copyAndReset(): CollectionAccumulator[T] = new CollectionAccumulator
// 实现 copy(), 返回CollectionAccumulator
  override def copy(): CollectionAccumulator[T] = {
    val newAcc = new CollectionAccumulator[T]
    _list.synchronized {
      newAcc._list.addAll(_list)
    }
    newAcc
  }
// 实现reset(), 原位操作
  override def reset(): Unit = _list.clear()
// 实现add(), 或者java list可以改为 mutable.List
  override def add(v: T): Unit = _list.add(v)
// 合并, match 模式匹配很好用,一堆try catch的作用, addAll
  override def merge(other: AccumulatorV2[T, java.util.List[T]]): Unit = other match {
    case o: CollectionAccumulator[T] => _list.addAll(o.value)
    case _ => throw new UnsupportedOperationException(
      s"Cannot merge ${this.getClass.getName} with ${other.getClass.getName}")
  }
// value的方法实现
  override def value: java.util.List[T] = _list.synchronized {
    java.util.Collections.unmodifiableList(new ArrayList[T](_list))
  }
// 新增方法, clear后设置新的list
  private[spark] def setValue(newValue: java.util.List[T]): Unit = {
    _list.clear()
    _list.addAll(newValue)
  }
}

自定义实现Set的累加器

class  LogAccumulator extends AccumulatorV2[String,java.util.Set[String]]{
  private val _logArray: java.util.Set[String] = new java.util.HashSet[String]()

  override def isZero: Boolean = {
    _logArray.isEmpty
  }

  override def reset(): Unit = {
    _logArray.clear()
  }

  override def add(v: String): Unit = {
    _logArray.add(v)
  }

  override def merge(other: AccumulatorV2[String, java.util.Set[String]]): Unit = {
    other match {
      case o: LogAccumulator => _logArray.addAll(o.value)
    }
  }

  override def value: java.util.Set[String] = {
    java.util.Collections.unmodifiableSet(_logArray)
  }

  override def copy(): AccumulatorV2[String, util.Set[String]] = {
    val newAcc = new LogAccumulator()
    _logArray.synchronized{
      newAcc._logArray.addAll(_logArray)
    }
    newAcc
  }
}

注:
1, java.util.Collections.unmodifiableSet 参考 https://www.yiibai.com/java/util/java_util_collections.html 此方法返回指定列表的不可修改视图。

累加器的坑:

1, spark RDD lazy操作, 可能导致累加器多加或少加,参照:http://blog.csdn.net/u013468917/article/details/70617085
所以使用完add累计器记得cache()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容