基于Spark下的自定义分区Demo

95 篇文章 0 订阅
29 篇文章 2 订阅

本demo所需的数据源:

链接: https://pan.baidu.com/s/1VEluh5B3HnodZFyoOZ9Zg 提取码: enmq 

import java.net.URL

import org.apache.spark.{Partitioner, SparkConf, SparkContext}

import scala.collection.mutable

object UrlPartition {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("UrlCountPartition").setMaster("local[2]")
    val sc = new SparkContext(conf)

    /**
      * 将数据切分,元组中放的是(Url,1)
      */
    val rdd1 = sc.textFile("E:\\sfy.log").
      map(line =>{
        val f = line.split("\t")
        (f(1),1)
      })

    /**
      * 统计相同的Url出现多少次
      */
    val rdd2 = rdd1.reduceByKey(_+_)
    /**
      * 将上一步的元素组合成我们想要的格式
      *
      * cache会将数据缓存到内存中,cache是一个Transformation,lazy
      */
    val rdd3 = rdd2.map(t=>{
      val url = t._1
      val host = new URL(url).getHost
      (host,(url,t._2))
    }).cache()
    /**
      * 进行自定义的分区
      */
    val ints = rdd3.map(_._1).distinct().collect()

    val hostPartitioner = new HostPartitioner(ints)

    /*源码
    def partitionBy(partitioner : org.apache.spark.Partitioner) :
    org.apache.spark.rdd.RDD[scala.Tuple2[K, V]] = {
      /* compiled code */ }
    */
    val rdd4 = rdd3.partitionBy(hostPartitioner).mapPartitions(t=>{
      t.toList.sortBy(_._2._2).reverse.take(2).iterator
    })
    rdd4.saveAsTextFile("E:\\outfile1")
    sc.stop()
  }
}
/*源码abstract class Partitioner() extends scala.AnyRef with scala.Serializable {
  def numPartitions : scala.Int
  def getPartition(key : scala.Any) : scala.Int
}
object Partitioner extends scala.AnyRef with scala.Serializable {
  def defaultPartitioner(rdd : org.apache.spark.rdd.RDD[_], others : org.apache.spark.rdd.RDD[_]*) : org.apache.spark.Partitioner = { /* compiled code */ }
}*/
class HostPartitioner(ints:Array[String])extends Partitioner{
  /**
    * (_,0)(_,1)(_,2)
    */
  val partMap = new mutable.HashMap[String,Int]()
  var count = 0
  for (i <- ints){
    partMap += (i -> count)
    count += 1
  }
  override def numPartitions: Int = ints.length

  override def getPartition(key: Any): Int = {
    partMap.getOrElse(key.toString,0)
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值