把SparkStreaming版本的wordcount写入mysql数据库

 
  
  1. package sparkstreamday01.SparkStream
  2. import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
  3. import org.apache.log4j.{Level, Logger}
  4. import org.apache.spark.SparkConf
  5. import org.apache.spark.rdd.RDD
  6. import org.apache.spark.streaming.dstream.ReceiverInputDStream
  7. import org.apache.spark.streaming.{Seconds, StreamingContext}
  8. object StreamRddsql3 {
  9. //设置日志级别WARN
  10. Logger.getLogger("org").setLevel(Level.WARN)
  11. def main(args: Array[String]): Unit = {
  12. //本地运行设置
  13. val conf: SparkConf = new SparkConf()
  14. .setMaster("local[3]") //至少两个核(运行一个,接收一个)
  15. .setAppName(this.getClass.getSimpleName)
  16. //StreamingContext
  17. val ssc = new StreamingContext(conf, Seconds(4))
  18. //接受socket信息 创建Dstream
  19. val text: ReceiverInputDStream[String] = ssc.socketTextStream("Linux00", 9999)
  20. //转换成RDD
  21. text.foreachRDD(rdd => {
  22. val result: RDD[(String, Int)] = rdd.flatMap(_.split(" ")).map((_, 1)).reduceByKey(_ + _)
  23. result.foreach(println)
  24. //写入数据库
  25. result.foreachPartition(p => {
  26. val conn: Connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/wjy1?characterEncoding=utf-8", "wjy1", "351991")
  27. val statement: PreparedStatement = conn.prepareStatement("create table if not exists wordcount3 (word varchar(20),total int)")
  28. statement.executeUpdate()
  29. //创建连接
  30. p.foreach(t => {
  31. //如果插入的单词已经存在数据库中,则更新这个单词的值(当前出现的次数+数据库当前的次数)
  32. val statement1: PreparedStatement = conn.prepareStatement("select * from wordcount3 where word=?")
  33. statement1.setString(1, t._1)
  34. val set: ResultSet = statement1.executeQuery()
  35. if (set.next()) {
  36. val count: Int = set.getInt("total")
  37. val newcount: Int = count + t._2
  38. //更新
  39. val statement2: PreparedStatement = conn.prepareStatement("update wordcount3 set total=? where word=?")
  40. statement2.setInt(1,newcount)
  41. statement2.setString(2,t._1)
  42. statement2.executeUpdate()
  43. }else{
  44. val statement3: PreparedStatement = conn.prepareStatement("insert into wordcount3 values(?,?)")
  45. statement3.setString(1,t._1)
  46. statement3.setInt(2,t._2)
  47. statement3.executeUpdate()
  48. }
  49. })
  50. conn.close()
  51. })
  52. })
  53. //启动主程序
  54. ssc.start()
  55. //阻塞 等待程序被关闭
  56. ssc.awaitTermination()
  57. }
  58. }

你可能感兴趣的:(把SparkStreaming版本的wordcount写入mysql数据库)