【问题标题】:Unable to use a new SparkSession after stopping the previous one停止前一个 SparkSession 后无法使用新的 SparkSession
【发布时间】:2018-04-09 19:05:51
【问题描述】:

我创建了一个 SparkSession(使用 enabledHiveSupport())并在本地运行。 我想在一个 SparkSession 中执行一组 sql,停止它并启动另一个。

但是当我停止 SparkSession 并使用 SparkSession.builder() 获取新的 SparkSession 时,我得到了一个新的 SparkSession 对象,但 sql 失败并显示“另一个 Derby 实例可能已经启动了数据库..”

由于每个 JVM 只能有一个 SparkContext,这是否意味着我无法获取或创建 SparkSession,停止并重复?

有什么方法可以每次在新会话中执行一组 sql? (我知道有 SparkSession.newSession,但我也无法停止该会话,因为底层共享 SparkContext 将停止,对吗?)

【问题讨论】:

  • 为什么不能保持会话打开?
  • 我正在超越堆空间,因为我正在对不同的数据分区进行重复操作。我没有足够的经验说这是主要原因,但我认为一些旧数据框填充了会话中的堆空间。因此,我想清除会话。

标签: apache-spark apache-spark-sql


【解决方案1】:

您好,您可以按照官方文档使用 SparkSession.newSession 原因

SparkSession: 使用隔离的 SQL 配置启动新会话,临时表、注册函数是隔离的,但共享底层 SparkContext 和缓存数据。

Note
    Other than the SparkContext,all shared state is initialized lazily. This method will 
    force the initialization of the shared state to ensure that parent and child sessions 
    are set up with the same shared state. If the underlying catalog implementation is 
    Hive, this will initialize the metastore, which may take some time.

如何使用多个 spark 会话的示例代码

object WorkimngWithNewSession {
  def main(args: Array[String]): Unit = {

    // creating a new session
    val spark = SparkSession
                .builder()
                .appName("understanding session")
                .master("local[*]")
                .getOrCreate()

    import spark.implicits._
    val df = Seq("name","apple").toDF()

    df.createOrReplaceTempView("testTable") // do not call this in case of multiple spark session and if u are using this view in all of them.
    df.createOrReplaceGlobalTempView("testTable") // call this for multiple spark session

    spark.sql("SELECT * FROM testTable").show()
    // spark.stop()  // do not call this as it will stop sparkContext

    val newSpark = spark.newSession()
    newSpark.sql("SELECT * FROM global_temp.testTable").show() // call global view by using global_temp


    spark.stop() // if u want u can call this line in the end to close all spark session
  }
}

【讨论】:

  • 是的,这看起来可行。但我想了解为什么在创建新的 SparkSession 时(已验证之前的 SparkSession.sparkContext 已停止)并且新的 SparkSession.sparkContext 处于活动状态。由于我在 JVM 中任何时候都只有 1 个活动 SparkContext,为什么仍然出现错误?
  • @Punsh 我认为关闭 sparkSession 也会关闭 sparkContext。我也不喜欢。
猜你喜欢
  • 2018-09-23
  • 2023-02-15
  • 2017-04-11
  • 2018-04-04
  • 2019-03-18
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多