如何加载java属性文件并在Spark中使用?

dip*_*uru 21 java properties-file apache-spark

我想将Spark参数(如输入文件,输出文件)存储到Java属性文件中,并将该文件传递给Spark Driver.我使用spark-submit提交作业但找不到传递属性文件的参数.你有什么建议吗?

vij*_*mar 33

在这里,我找到了一个解

props文件:(mypropsfile.conf)// 注意:用"spark"键前缀你的键.否则道具将被忽略.

spark.myapp.input /input/path
spark.myapp.output /output/path
Run Code Online (Sandbox Code Playgroud)

发射

$SPARK_HOME/bin/spark-submit --properties-file  mypropsfile.conf
Run Code Online (Sandbox Code Playgroud)

如何调用代码 :(内部代码)

sc.getConf.get("spark.driver.host")  // localhost
sc.getConf.get("spark.myapp.input")       // /input/path
sc.getConf.get("spark.myapp.output")      // /output/path
Run Code Online (Sandbox Code Playgroud)

  • 警告,使用--properties-file会覆盖以前定义的任何spark-defaults.conf(http://spark.apache.org/docs/latest/submitting-applications.html),因此可能需要创建自己的合并版. (4认同)

Rah*_*rma 7

上一个答案的方法有限制,即每个属性应该spark在属性文件中开始 -

例如

spark.myapp.input
spark.myapp.output

如果假设您有一个不以spark以下内容开头的属性:

job.property:

app.name = XYZ

$SPARK_HOME/bin/spark-submit --properties-file  job.property
Run Code Online (Sandbox Code Playgroud)

Spark会忽略所有没有spark.带消息前缀的属性:

警告:忽略非spark配置属性:app.name = test

我如何在应用程序的驱动程序和执行程序中管理属性文件:

${SPARK_HOME}/bin/spark-submit --files job.properties
Run Code Online (Sandbox Code Playgroud)

用于访问缓存文件的Java代码(job.properties):

import java.util.Properties;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.SparkFiles;
import java.io.InputStream;
import java.io.FileInputStream;

//Load file to propert object using HDFS FileSystem
String fileName = SparkFiles.get("job.properties")
Configuration hdfsConf = new Configuration();
FileSystem fs = FileSystem.get(hdfsConf);

//THe file name contains absolute path of file
FSDataInputStream is = fs.open(new Path(fileName));

// Or use java IO
InputStream is = new FileInputStream("/res/example.xls");

Properties prop = new Properties();
//load properties
prop.load(is)
//retrieve properties
prop.getProperty("app.name");
Run Code Online (Sandbox Code Playgroud)

如果您具有特定于环境的属性,(dev/test/prod)则在以下位置提供APP_ENV自定义Java环境变量spark-submit:

${SPARK_HOME}/bin/spark-submit --conf \
"spark.driver.extraJavaOptions=-DAPP_ENV=dev spark.executor.extraJavaOptions=-DAPP_ENV=dev" \
--properties-file  dev.property
Run Code Online (Sandbox Code Playgroud)

替换您的驱动程序或执行程序代码:

//Load file to propert object using HDFS FileSystem
String fileName = SparkFiles.get(System.getProperty("APP_ENV")+".properties")
Run Code Online (Sandbox Code Playgroud)