Spark版本定制:三. SparkStreaming 透彻理解三板斧之三

感谢DT大数据梦工厂支持提供以下内容, 
DT大数据梦工厂专注于Spark发行版定制。详细信息请查看 
联系邮箱18610086859@126.com 
电话:18610086859 
QQ:1740415547 
微信号:18610086859

IMF晚8点大数据实战YY直播频道号:68917580


以计算电商中各类别中最热门的商品排名的应用程序作为切入点,进一步

理解Spark Streaming Job整个架构和运行机制

代码如下:

package sparksql.java.sparkStreaming

import org.apache.spark.SparkConf

import org.apache.spark.sql.Row

import org.apache.spark.sql.hive.HiveContext

import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}

import org.apache.spark.streaming.{Seconds, StreamingContext}

/**

  * 使用Spark Streaming+Spark SQL来在线动态计算电商中不同类别中最热门的商品排名,例如手机这个类别下面最热门的三种手机、电视这个类别

  * 下最热门的三种电视,该实例在实际生产环境下具有非常重大的意义;

  *

  * @author DT大数据梦工厂

  * 新浪微博:http://weibo.com/ilovepains/

  *

  *

  *   实现技术:Spark Streaming+Spark SQL,之所以Spark Streaming能够使用ML、sql、graphx等功能是因为有foreachRDD和Transform

  * 等接口,这些接口中其实是基于RDD进行操作,所以以RDD为基石,就可以直接使用Spark其它所有的功能,就像直接调用API一样简单。

  *  假设说这里的数据的格式:user item category,例如Rocky Samsung Android

  */

object OnlineTheTop3ItemForEachCategory2DB {

  def main(args: Array[String]){

    /**

      * 第1步:创建Spark的配置对象SparkConf,设置Spark程序的运行时的配置信息,

      * 例如说通过setMaster来设置程序要链接的Spark集群的Master的URL,如果设置

      * 为local,则代表Spark程序在本地运行,特别适合于机器配置条件非常差(例如

      * 只有1G的内存)的初学者       *

      */

    val conf = new SparkConf() //创建SparkConf对象

    conf.setAppName("OnlineTheTop3ItemForEachCategory2DB") //设置应用程序的名称,在程序运行的监控界面可以看到名称

//    conf.setMaster("spark://Master:7077") //此时,程序在Spark集群

    conf.setMaster("local[6]")

    //设置batchDuration时间间隔来控制Job生成的频率并且创建Spark Streaming执行的入口

    val ssc = new StreamingContext(conf, Seconds(5))

    ssc.checkpoint("/root/Documents/SparkApps/checkpoint")

    val userClickLogsDStream = ssc.socketTextStream("Master", 9999)

    val formattedUserClickLogsDStream = userClickLogsDStream.map(clickLog =>

        (clickLog.split(" ")(2) + "_" + clickLog.split(" ")(1), 1))

//    val categoryUserClickLogsDStream = formattedUserClickLogsDStream.reduceByKeyAndWindow((v1:Int, v2: Int) => v1 + v2,

//      (v1:Int, v2: Int) => v1 - v2, Seconds(60), Seconds(20))

    val categoryUserClickLogsDStream = formattedUserClickLogsDStream.reduceByKeyAndWindow(_+_,

      _-_, Seconds(60), Seconds(20))

    categoryUserClickLogsDStream.foreachRDD { rdd => {

      if (rdd.isEmpty()) {

        println("No data inputted!!!")

      } else {

        val categoryItemRow = rdd.map(reducedItem => {

          val category = reducedItem._1.split("_")(0)

          val item = reducedItem._1.split("_")(1)

          val click_count = reducedItem._2

          Row(category, item, click_count)

        })

        val structType = StructType(Array(

          StructField("category", StringType, true),

          StructField("item", StringType, true),

          StructField("click_count", IntegerType, true)

        ))

        val hiveContext = new HiveContext(rdd.context)

        val categoryItemDF = hiveContext.createDataFrame(categoryItemRow, structType)

        categoryItemDF.registerTempTable("categoryItemTable")

        val reseltDataFram = hiveContext.sql("SELECT category,item,click_count FROM (SELECT category,item,click_count,row_number()" +

          " OVER (PARTITION BY category ORDER BY click_count DESC) rank FROM categoryItemTable) subquery " +

          " WHERE rank <= 3")

        reseltDataFram.show()

        val resultRowRDD = reseltDataFram.rdd

        resultRowRDD.foreachPartition { partitionOfRecords => {

          if (partitionOfRecords.isEmpty){

            println("This RDD is not null but partition is null")

          } else {

            // ConnectionPool is a static, lazily initialized pool of connections

            val connection = ConnectionPool.getConnection()

            partitionOfRecords.foreach(record => {

              val sql = "insert into categorytop3(category,item,client_count) values('" + record.getAs("category") + "','" +

                record.getAs("item") + "'," + record.getAs("click_count") + ")"

              val stmt = connection.createStatement();

              stmt.executeUpdate(sql);

            })

            ConnectionPool.returnConnection(connection) // return to the pool for future reuse

          }

        }

        }

      }

    }

    }

   ssc.start()

    ssc.awaitTermination()

  }

}

运行说明:

     1、在StreamingContext调用start方法的内部其实是会启动JobScheduler的Start方法:

// 在新的线程里开始流式调度,在不影响当前线程的情况下,线程的局部属性如调用点和工作组将被重置。
ThreadUtils.runInNewThread("streaming-start") {
  sparkContext.setCallSite(startSite.get)
  sparkContext.clearJobGroup()
  sparkContext.setLocalProperty(SparkContext.SPARK_JOB_INTERRUPT_ON_CANCEL, "false")
  scheduler.start()
}

在JobScheduler的start内部会构造JobGenerator和ReceiverTacker,并且调用JobGenerator和ReceiverTacker的start方法:

receiverTracker = new ReceiverTracker(ssc)
inputInfoTracker = new InputInfoTracker(ssc)
executorAllocationManager = ExecutorAllocationManager.createIfEnabled(
  ssc.sparkContext,
  receiverTracker,
  ssc.conf,
  ssc.graph.batchDuration.milliseconds,
  clock)
executorAllocationManager.foreach(ssc.addStreamingListener)
receiverTracker.start()
jobGenerator.start()

2、ReceiverTracker启动后首先在Spark Cluster中启动Receiver(其实是在Executor中先启动ReceiverSupervisor),在Receiver收到数据后会通过ReceiverSupervisor存储到Executor并且把数据的Metadata信息发送给Driver中的ReceiverTracker,在ReceiverTracker内部会通过ReceivedBlockTracker来管理接受到的元数据信息

/** Start the endpoint and receiver execution thread. */
def start(): Unit = synchronized {
 if (isTrackerStarted) {
   throw new SparkException("ReceiverTracker already started")
 }

 if (!receiverInputStreams.isEmpty) {
   endpoint = ssc.env.rpcEnv.setupEndpoint(
     "ReceiverTracker", new ReceiverTrackerEndpoint(ssc.env.rpcEnv))
   if (!skipReceiverLaunch) launchReceivers()
   logInfo("ReceiverTracker started")
   trackerState = Started
 }
}

private val receivedBlockTracker = new ReceivedBlockTracker(
 ssc.sparkContext.conf,
 ssc.sparkContext.hadoopConfiguration,
 receiverInputStreamIds,
 ssc.scheduler.clock,
 ssc.isCheckpointPresent,
 Option(ssc.checkpointDir)
)
// Local messages
case StartAllReceivers(receivers) =>
 val scheduledLocations = schedulingPolicy.scheduleReceivers(receivers, getExecutors)
 for (receiver <- receivers) {
   val executors = scheduledLocations(receiver.streamId)
   updateReceiverScheduledExecutors(receiver.streamId, executors)
   receiverPreferredLocations(receiver.streamId) = receiver.preferredLocation
   startReceiver(receiver, executors)
 }
// Function to start the receiver on the worker node
val startReceiverFunc: Iterator[Receiver[_]] => Unit =
 (iterator: Iterator[Receiver[_]]) => {
   if (!iterator.hasNext) {
     throw new SparkException(
       "Could not start receiver as object not found.")
   }
   if (TaskContext.get().attemptNumber() == 0) {
     val receiver = iterator.next()
     assert(iterator.hasNext == false)
     val supervisor = new ReceiverSupervisorImpl(
       receiver, SparkEnv.get, serializableHadoopConf.value, checkpointDirOption)
     supervisor.start()
     supervisor.awaitTermination()
   } else {
     // It's restarted by TaskScheduler, but we want to reschedule it again. So exit it.
   }
 }

// Create the RDD using the scheduledLocations to run the receiver in a Spark job
val receiverRDD: RDD[Receiver[_]] =
 if (scheduledLocations.isEmpty) {
   ssc.sc.makeRDD(Seq(receiver), 1)
 } else {
   val preferredLocations = scheduledLocations.map(_.toString).distinct
   ssc.sc.makeRDD(Seq(receiver -> preferredLocations))
 }
receiverRDD.setName(s"Receiver $receiverId")
ssc.sparkContext.setJobDescription(s"Streaming job running receiver $receiverId")
ssc.sparkContext.setCallSite(Option(ssc.getStartSite()).getOrElse(Utils.getCallSite()))

 3、每个BatchInterval会产生一个具体的Job,其实这里的Job不是Spark Core中所指的Job,它只是基于DStreamGraph而生成的RDD的DAG而已,从Java角度讲,相当于Runnable接口实例,此时要想运行Job需要提交给JobScheduler,在JobScheduler中通过线程池的方式找到一个单独的线程来提交Job到集群运行(其实是在线程中基于RDD的Action触发真正的作业的运行),为什么使用线程池呢?

       1,作业不断生成,所以为了提升效率,我们需要线程池;这和在Executor中通过线程池执行Task有异曲同工之妙;

        2,有可能设置了Job的FAIR公平调度的方式,这个时候也需要多线程的支持;

ReceiverSupervisor中:

/** Start receiver */
def startReceiver(): Unit = synchronized {
 try {
   if (onReceiverStart()) {
     logInfo(s"Starting receiver $streamId")
     receiverState = Started
     receiver.onStart()
     logInfo(s"Called receiver $streamId onStart")
   } else {
     // The driver refused us
     stop("Registered unsuccessfully because Driver refused to start receiver " + streamId, None)
   }
 } catch {
   case NonFatal(t) =>
     stop("Error starting receiver " + streamId, Some(t))
 }
}

在Receiver子类以

onStart方法

val executorPool =
  ThreadUtils.newDaemonFixedThreadPool(topics.values.sum, "KafkaMessageHandler")
try {
  // Start the messages handler for each partition
  topicMessageStreams.values.foreach { streams =>
    streams.foreach { stream => executorPool.submit(new MessageHandler(stream)) }
  }
} finally {
  executorPool.shutdown() // Just causes threads to terminate after work is done
}
  
// Handles Kafka messages
private class MessageHandler(stream: KafkaStream[K, V])
  extends Runnable {
  def run() {
    logInfo("Starting MessageHandler.")
    try {
      val streamIterator = stream.iterator()
      while (streamIterator.hasNext()) {
        val msgAndMetadata = streamIterator.next()
        store((msgAndMetadata.key, msgAndMetadata.message))
      }
    } catch {
      case e: Throwable => reportError("Error handling message; exiting", e)
    }
  }
}

转载于:https://my.oschina.net/DTSpark/blog/672491

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值