SparkStreaming foreachPartition实现输出数据到MYSQL

本文介绍如何使用Apache Spark Streaming进行实时数据流处理,并将处理结果写入MySQL数据库。通过Socket接收数据,使用Spark RDD进行词频统计,最后将统计结果前三位保存到MySQL中。涉及Spark配置、数据流接收、词频统计窗口操作及MySQL集成。
import java.sql.DriverManager

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

object foreachTOMysql {

  def writeToMysql()={
    val conf = new SparkConf().setMaster("local[*]").setAppName("MYsql")
    val ssc = new StreamingContext(conf,Seconds(5))
    val ItemStream = ssc.socketTextStream("192.168.59.100",8888)
    val ItemPairs = ItemStream.map({
      line =>
        (line.split(",")(0),1)
    })
    val ItemCount = ItemPairs.reduceByKeyAndWindow((v1:Int,v2:Int)=>v1+v2,Seconds(60),Seconds(10))
    val hottestWord = ItemCount.transform(itemRDD =>{
        val top3 = itemRDD.map(pair=>(pair._2,pair._1))
          .sortByKey(false)
          .map(pair=>(pair._2,pair._1))
          .take(3)
      ssc.sparkContext.makeRDD(top3)
      })
    hottestWord.foreachRDD(rdd=>{
      rdd.foreachPartition(partitionOfReconds=>{
        val url = "jdbc:mysql://192.168.59.100:3306/spark"
        val username = "root"
        val password = "123456"
        Class.forName("com.mysql.jdbc.Driver")
        val conn = DriverManager.getConnection(url,username,password)
        conn.prepareStatement("").executeUpdate()
        conn.setAutoCommit(false)
        val stmt = conn.createStatement()
        partitionOfReconds.foreach(recond=>{
          stmt.addBatch("")
        })
        stmt.executeBatch()
        conn.commit()
      })
    })
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()
  }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值