开发者社区> 问答> 正文

spark streaming 程序中存在多个foreachRDD操作存到mysql?

针对单个foreachRDD操作可以mysql的事务处理,多个的情况怎么做呀?有遇到这个问题吗?

本问题来自阿里云开发者社区的【11大垂直技术领域开发者社群】。点击链接欢迎加入感兴趣的技术领域群

展开
收起
珍宝珠 2019-10-24 16:48:00 519 0
1 条回答
写回答
取消 提交回答
  • import java.sql.DriverManager import org.apache.spark.SparkConf import org.apache.spark.streaming.{Seconds, StreamingContext} object ForeachRDDApp {   def main(args: Array[String]) {     val sparkConf = new SparkConf()       .setAppName("ForeachRDDApp")       .setMaster("local[2]")     val ssc = new StreamingContext(sparkConf, Seconds(10))     val lines = ssc.socketTextStream("hadoop000",9997)     val results = lines.flatMap(.split(",")).map((,1)).reduceByKey(+)     // TODO... 将results写入到MySQL中 //    results.foreachRDD(rdd => { //        rdd.foreach(x => { //          val connection = createConnection() //          val word = x._1 //          val count = x._2.toInt //          val sql = s"insert into wc(word, c) values ('$word', $count)" //          connection.createStatement().execute(sql) //        }) //    })     // 最佳实践     results.foreachRDD(rdd => {       rdd.foreachPartition(partition => {         val connection = createConnection()         partition.foreach(x => {           val word = x._1           val count = x._2.toInt           val sql = s"insert into wc(word, c) values ('$word', $count)"           connection.createStatement().execute(sql)         })         connection.close()       })       rdd.foreach(x => {         val connection = createConnection()         val word = x._1         val count = x._2.toInt         val sql = s"insert into wc(word, c) values ('$word', $count)"         connection.createStatement().execute(sql)       })     })     ssc.start()  // 一定要写 //    lines.print()     ssc.awaitTermination()   }   def createConnection() = {     Class.forName("com.mysql.jdbc.Driver")     DriverManager.getConnection("jdbc:mysql://hadoop000:3306/ss2","root","root")   } } 答案来源网络,供参考 原文链接:https://blog.csdn.net/qq_15300683/article/details/80689998

    2019-10-25 10:36:19
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
阿里云MySQL云数据库产品体系介绍 立即下载
One Box: 解读事务与分析一体化数据库 HybridDB for MySQL 立即下载
One Box:解读事务与分析一体化数据库HybridDB for MySQL 立即下载

相关镜像