spark读取外部配置文件的方法
spark-submit --files /tmp/fileName /tmp/test.jar
使用spark提交时使用--files参数,spark会将将本地的文件上传的hdfs,而后分发给每一个executorjava
在程序中只须要使用文件名获取数据shell
val filePath ="fileName"测试
val props =newProperties()this
props.load(newFileInputStream(filePath))spa
//发送到executor去执行scala
val rdd=sc.parallelize(0to3)3d
rdd.foreach(index=>code
props.keySet().toArray().foreach(x=>println(x+"\t"+props.getProperty(x.toString)))blog
)资源
java的方式也是同样的,在这就不写了
三、--files ./config.properties
读通常文件:
val t: BufferedSource = scala.io.Source.fromFile("config.properties") t.getLines().foreach(t=>println(t))
读配置文件:
/* val config = "config.properties" val prop = new Properties() prop.load(new FileInputStream(config)) val keyset = prop.keySet().toArray() keyset.foreach(t=>println(t+" "+prop.getProperty(t.toString)))*/
配置文件类加载测试 | 配置采用 key=value 的形式 | client/cluster | 采用 sc.getConf.get 方法;配合submit 参数–properties-file 上传配置文件; 配置文件key value 以空格为分隔符 |
配置文件类加载测试 | 配置采用 key=value 的形式 | client/cluster | 采用java.util.Properties 方法;配置文件打包到jar包里; 配置文件key value 以“=”为分隔符 |
资源文件类加载测试 | 普通文本格式,非key value模式 | client/cluster | 采用scala.io.Source.fromFile 方法;资源文件采用submit 参数–files 上传; |
资源文件类加载测试 | 普通文本格式,非key value模式 | client/cluster | 采用scala.io.Source.fromFile和getResourceAsStream方法;资源文件打包到jar包中; |
在/tmp下建立a文件,内容为:
this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data
spark-shell --master yarn --files "/tmp/a"
能够看到a文件被上传到hdfs上了:
在代码中读取该文件,以下
能够看见这个文件在excutor被正确读取:且在两个excutor上分别执行,一个打印了22行,一个打印11行,原文件总共11行;上述rdd公有三个元素,每一个元素遍历时打印一遍,总共
3*11=33