spark向mysql写数据类型_使用SparkStreaming实现将数据写到MySQL中

引入依赖

mysql

mysql-connector-java

5.1.38

commons-dbcp

commons-dbcp

1.4

使用Java编写一个数据库连接池类

package cn.itcast.spark.day7;

import java.sql.Connection;

import java.sql.DriverManager;

import java.util.LinkedList;

public class ConnectionPool {

private static LinkedList connectionQueue;

static {

try {

Class.forName("com.mysql.jdbc.Driver");

}catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

public synchronized static Connection getConnection() {

try {

if (connectionQueue == null) {

connectionQueue = new LinkedList();

for (int i = 0;i < 5;i ++) {

Connection conn = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true",

"root",

"root"

);

connectionQueue.push(conn);

}

}

}catch (Exception e) {

e.printStackTrace();

}

return connectionQueue.poll();

}

public static void returnConnection(Connection conn) {

connectionQueue.push(conn);

}

}

spark代码

package cn.itcast.spark.day7

import org.apache.spark.{SparkConf, TaskContext}

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

object sqlTest {

def main(args: Array[String]){

val conf = new SparkConf().setMaster("local[2]").setAppName("w")

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

val lines = ssc.socketTextStream("101.132.122.75",9999)

val words = lines.flatMap(_.split(" "))

val wordcount = words.map(x => (x,1)).reduceByKey(_+_)

wordcount.foreachRDD(rdd => {

//rdd不为空执行插入代码

if(rdd.isEmpty!){

rdd.foreachPartition(eachPartition => {

val conn = ConnectionPool.getConnection();

eachPartition.foreach(record => {

val sql = "insert into streaming(item,count) values('" + record._1 + "'," + record._2 + ")"

val stmt = conn.createStatement

stmt.executeUpdate(sql)

})

ConnectionPool.returnConnection(conn)

})

}

})

ssc.start()

ssc.awaitTermination()

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值