sparkStraming儲存資料到mysql

來源:互聯網
上載者:User

標籤:exce   value   tor   cut   set   opera   order   man   nec   

package sparkStreamingimport org.apache.spark.SparkConfimport org.apache.spark.streaming.Secondsimport org.apache.spark.streaming.StreamingContextimport org.apache.spark.streaming.kafka.KafkaUtilsimport org.apache.spark.HashPartitionerimport org.apache.spark.streaming.Durationimport org.apache.spark.sql.SQLContext import org.apache.spark.{SparkContext, SparkConf} import spark.bean.ordersimport java.util.Properties import java.sql.{DriverManager, PreparedStatement, Connection}  import org.apache.spark.{SparkContext, SparkConf}  object WebPagePopularityValueCalculator {  def main(args: Array[String]) {    val Array(zkQuorum, group, topics) = Array("localhost:2181", "1", "sun_test_topic")    val sparkConf = new SparkConf().setAppName("KafkaWordCount").setMaster("local[2]")    val ssc = new StreamingContext(sparkConf, Seconds(2))    ssc.checkpoint("checkpoint")    val topicpMap = topics.split(",").map((_, 2)).toMap        val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicpMap).map(_._2)    val popularityData = lines.map { msgLine =>      {        val dataArr: Array[String] = msgLine.split("\\|")        val pageID = dataArr(0)        val popValue: Double = dataArr(1).toFloat * 0.8 + dataArr(2).toFloat * 0.8 + dataArr(3).toFloat * 1        (pageID, popValue)      }    }    //sum the previous popularity value and current value    val updatePopularityValue = (iterator: Iterator[(String, Seq[Double], Option[Double])]) => {      iterator.flatMap(t => {        val newValue: Double = t._2.sum        val stateValue: Double = t._3.getOrElse(0);        Some(newValue + stateValue)      }.map(sumedValue => (t._1, sumedValue)))    }    val initialRDD = ssc.sparkContext.parallelize(List(("page1", 0.00)))    val stateDstream = popularityData.updateStateByKey[Double](updatePopularityValue,      new HashPartitioner(ssc.sparkContext.defaultParallelism), true, initialRDD)    //set the checkpoint interval to avoid too frequently data checkpoint which may    //may significantly reduce operation throughput    stateDstream.checkpoint(Duration(8 * 2 * 1000))    //after calculation, we need to sort the result and only show the top 10 hot pages    stateDstream.foreachRDD { rdd =>      {        val sortedData = rdd.map { case (k, v) => (v, k) }.sortByKey(false)        val topKData = sortedData.take(10).map { case (v, k) => (k, v) }        topKData.foreach{ case (k, v) =>           if(v != 0) {             println("page" + k + "  " + "value" + v)             val itb = Iterator((k, v))             toMySql(itb)          }                  }              }    }    ssc.start()    ssc.awaitTermination()  }    def toMySql(iterator: Iterator[(String, Double)]): Unit = {        var conn: Connection = null          var ps: PreparedStatement = null          val sql = "insert into userbehavior(page, number) values (?, ?)"          try {              Class.forName("com.mysql.jdbc.Driver");              conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spark", "root", "[email protected]")              iterator.foreach(dataIn => {                  ps = conn.prepareStatement(sql)                  ps.setString(1, dataIn._1)                  ps.setDouble(2, dataIn._2)                  ps.executeUpdate()              }              )          } catch {              case e: Exception => e.printStackTrace()          } finally {              if (ps != null) {                  ps.close()          }              if (conn != null) {                  conn.close()              }          }    }  }  

 

sparkStraming儲存資料到mysql

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.