【问题标题】:When use foreachPartition to write data in rdd into mysql , i lost mysql connection occasionally当使用foreachPartition将rdd中的数据写入mysql时,我偶尔会丢失mysql连接
【发布时间】:2019-08-20 09:41:18
【问题描述】:

我使用spark rdd将数据写入mysql,我使用的运算符是foreachPartition,在运算符中我设置连接池并写入数据(使用scalike jdbc的),然后破坏池,但是似乎连接池偶尔找不到,日志说Connection pool is not yet initialized. (name:'xxx),不知道为什么会这样

数据终于全部插入了。但是异常让我很困惑

【问题讨论】:

    标签: mysql apache-spark rdd scalikejdbc


    【解决方案1】:

    我相信你已经以同样的方式实现了(如果使用 java 的话)

    dstream.foreachRDD(rdd -> {
    
      rdd.foreachPartition(partitionOfRecords -> {
    
        Connection connection = createNewConnection();
        while (partitionOfRecords.hasNext()) {
          connection.send(partitionOfRecords.next());
        }
        connection.close();
      });
    });
    

    在 createNewConnection() 方法中,您只需实现单例连接对象模式并离开而不关闭。

    dstream.foreachRDD(rdd -> {
    
      rdd.foreachPartition(partitionOfRecords -> {
    
        Connection connection = ConnectionObject.singleTonConnection();
        while (partitionOfRecords.hasNext()) {
          connection.send(partitionOfRecords.next());
        }
    
      });
    });
    

    //单例方法应该是这样的

    public class ConnectionObject (){
    
    
    private static Connection=null;
    
    public static Connection singleTonConnection(){
    
    if(Connection !=null){
    
    /** get new connection from spring data source or jdbc client**/
    
    }
    return Connection;
    
    }
    }
    

    【讨论】:

    • 感谢您的评论。但我有两个问题。 1.singleTonConnection() 是否会影响我是否获得连接。我认为它只能节省一些资源 2. 对于 Spark 作业中的每个分区被分成不同的任务,如果它们在不同的线程中工作,它们可以共享相同的连接吗?
    • 这里我们实现了单例连接对象,static变量连接对于一个JVM来说是相同的。因此,foreach 分区将在同一个执行程序上执行,即同一个 JVM,因此相同的连接将可用。如果有答案,请点赞。
    • 它实际上可能会节省建立连接的资源并经常破坏它。但我认为这不是您描述的第一种方式无法找到连接的原因
    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 2017-11-05
    • 2021-08-22
    • 1970-01-01
    • 2019-12-31
    • 2016-08-04
    相关资源
    最近更新 更多