在做spark時,有些時候需要加載資源文件,需要在driver或者worker端訪問。在client模式下可以使用IO流直接讀取,但是在cluster模式下卻不能直接讀取,需要如下代碼:
val is: InputStream = this.getClass.getResourceAsStream(“./xxx.sql”) val bufferSource = Source.fromInputStream(is)
這是直接讀取classPath路徑下的文件,但是cluster模式下,driver有可能不再程序提交的客戶端上,以上代碼會發生空指針異常。這是,就需要通過--files把外部資源文件加載到classpath路徑下。正常情況加載---files filename1,filename2....,當知道外部源文件都是有哪些時,直接列舉出來就可以。但是在某些情況下,開發者開發的是一個通用工具,不知到所要加載的是一個什么文件。這時就需要動態加載,我曾嘗試過使用--files ../xxx/*.sql,這個可以動態加載指定目錄下數據。但是后來發現,這樣加載只能加載一個文件,文件夾中超過多余一個文件就會報錯。試了很多種方式也沒有測試成功。最后通過shell腳本列舉文件夾中的文件拼裝成字符串,才算完成。
程序打包目錄如下:
代碼實現如下:
########################################################################################## ####由於spark2_submit --files /../*.sql 不能加載多個文件所以只能拼裝script路徑下的文件#### ########################################################################################## ###獲取當前項目絕對路徑### #project_home=$(dirname $(readlink -f "$0"))"/.." project_home="$(readlink -f $(cd "`dirname "$0"`"/..; pwd))" ###獲取script絕對路徑### script_path=${project_home}"/script/" ###獲取項目中script目錄下所有的腳本文件 files=$(ls $script_path); files=${files// / }; file_arr=($files); files_str="" for ele in ${file_arr[*]} do file_str=${file_str}${script_path}${ele}, done len=`expr ${#file_str} - 1` file_str=`expr substr "$file_str" 1 $len` echo $file_str /usr/bin/spark2-submit --executor-memory 15G \ --master yarn \ --queue dataengine \ --files $project_home/script/* \ --executor-cores 5 \ --driver-cores 3 \ --name AutoScript \ --deploy-mode cluster \ --class xx.xx.xxx \ --driver-memory 10G \ --conf "spark.dynamicAllocation.executorIdleTimeout=300" \ --conf "spark.shuffle.file.buffer=16k" \ --conf "spark.yarn.appMasterEnv.JAVA_HOME=/opt/jdk1.8.0_45" \ --conf "spark.dynamicAllocation.minExecutors=11" \ --conf "spark.dynamicAllocation.maxExecutors=11" \ --conf "spark.speculation.quantile=0.85" \ --conf "spark.executorEnv.JAVA_HOME=/opt/jdk1.8.0_45" \ --conf "spark.executor.extraJavaOptions=-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:+UseG1GC " \ --conf "spark.executor.extraJavaOptions=-XX:+UseG1GC " \ --conf "spark.driver.extraClassPath=/home/sunkl/hive-exec-1.1.0-cdh5.7.6.jar" \ --conf "spark.speculation=true" \ --conf "spark.rpc.askTimeout=400" \ --conf "spark.shuffle.service.enabled=true" \ $project_home/lib/******.jar