如何从 Java Spark 应用程序读取 app.properties 文件

How to read app.properties file from Java Spark application

我实现了 Java Spark 应用程序,我在 EMR 集群上 运行 使用 spark-submit 命令。 我想传递我在应用程序中使用的 app.properties 。 app.properties 看起来如下:

local_fetcher = false
local_storage = false
local_db = true
.
.
.

我希望能够在我的应用程序中获取这些数据。 我的问题是:

  1. app.properties 应该位于何处?
  2. 如何在我的 Spark 应用程序中读取它的内容?
  3. 我应该能够从驱动程序和执行程序中读取它吗?

我尝试使用 --properties-file 标志,但我知道它会覆盖默认的 Spark 配置,这不是我想要的。 我看到我可以使用 --file 标志,但不明白文件应该放在哪里以及如何在我的应用程序中读取它。

第一个选项:--files

--files FILES Comma-separated list of files to be placed in the working directory of each executor. File paths of these files in executors can be accessed via SparkFiles.get(fileName).

spark-submit --files /path/to/app.properties /path/to/your/fat/jar.jar

您可以使用 SparkFiles.

获取上传文件的确切位置

第二个选项:getResourceAsStream

将您的 app.properties 放入作业的 JAR 文件中,然后像这样加载它:

val appPropertiesStream = scala.io.Source.fromInputStream(
  classOf[yourObject].getClassLoader.getResourceAsStream("/app.properties")

val appPropertiesString = scala.io.Source.fromInputStream(appPropertiesStream ).mkString

(注意“app.properties”前的正斜杠,我记得很重要)