Spark Structured Streaming ForeachWriter和数据库性能

时间:2017-10-18 22:22:46

标签: database scala apache-spark jdbc spark-structured-streaming

我已经实现了像这样的结构化流......

myDataSet
  .map(r =>  StatementWrapper.Transform(r))
  .writeStream
  .foreach(MyWrapper.myWriter)
  .start()
  .awaitTermination()

这一切似乎都有效,但是看看MyWrapper.myWriter的吞吐量是可怕的。它有效地试图成为JDBC接收器,它看起来像:

val myWriter: ForeachWriter[Seq[String]] = new ForeachWriter[Seq[String]] {

  var connection: Connection = _

  override def open(partitionId: Long, version: Long): Boolean = {
    Try (connection = getRemoteConnection).isSuccess
  }

  override def process(row: Seq[String]) {
    val statement = connection.createStatement()
    try {
      row.foreach( s => statement.execute(s) )
    } catch {
      case e: SQLSyntaxErrorException => println(e)
      case e: SQLException => println(e)
    } finally {
      statement.closeOnCompletion()
    }
  }

  override def close(errorOrNull: Throwable) {
    connection.close()
  }
}

所以我的问题是 - 新的ForeachWriter是否为每一行实例化?因此,为数据集中的每一行调用open()和close()?

是否有更好的设计来提高吞吐量?

如何解析SQL语句一次并执行多次,同时保持数据库连接打开?

1 个答案:

答案 0 :(得分:8)

打开和关闭底层接收器取决于 ForeachWriter的实现

调用ForeachWriter的相关类是ForeachSink,这是调用你的作者的代码:

data.queryExecution.toRdd.foreachPartition { iter =>
  if (writer.open(TaskContext.getPartitionId(), batchId)) {
    try {
      while (iter.hasNext) {
        writer.process(encoder.fromRow(iter.next()))
      }
    } catch {
      case e: Throwable =>
        writer.close(e)
        throw e
    }
    writer.close(null)
  } else {
    writer.close(null)
  }
}

尝试打开和关闭作者,从源生成的foreach批处理。如果您希望每次都openclose打开并关闭接收器驱动程序,则需要通过实施来执行此操作。

如果您想要更好地控制数据的处理方式,可以实现Sink特征,该特征提供批次ID和基础DataFrame

trait Sink {
  def addBatch(batchId: Long, data: DataFrame): Unit
}