1. 批任务整体流程:
import org.apache.spark.sql.SparkSession
import org.slf4j.LoggerFactory//高性能日志
object test{
private val LOGGER = LoggerFactory.getLogger(this.getClass)
def main(args: Array[String]): Unit = {
args.foreach(x => Util.infoLog(LOGGER, s"****args: ${x} ****")
)
val inputSql=args(0)
val inputSchema=args(1).split(",")
val defaultPartitions=args(2).toInt
val sc = SparkSession.builder().enableHiveSupport().getOrCreate()
import sc.implicits._
try{
val inputDocsDF = sc.sql(inputSql).repartition(defaultPartitions)
.rdd.map {
row =>
val docSql = row.toSeq.asInstanceOf[Seq[String]].toArray
//.toBuffer.asInstanceOf[ArrayBuffer[String]] //可变长度,适用于schema要增加的情况
docSql
//做正式处理
}
} finally {
if (null != sc) {
//清空persist的rdd
sc.sparkContext.getPersistentRDDs.foreach(x => x._2.unpersist())//rdd,dataframe都适用,因为底层都是rdd
//sc.catalog.uncacheTable(tableName) //用于清空指定表,不存在会报错
//sc.catalog.clearCache() //清空所有cache(),不包括disk,如果cache了tempView,则需要用该方法清除
sc.stop
}
}
}
}
2.加载hdfs文件:
import org.apache.hadoop.fs.{FileSystem, Path}
val hdfsHead = filePath.split("\\/").take(3).mkString("/")
val hdfs=org.apache.hadoop.fs.FileSystem.get(new java.net.URI(hdfsHead), new org.apache.hadoop.conf.Configuration())
if (hdfs.exists(new Path(filePath))) {
val filelines = sparkContext.textFile(filePath).collect().filter(x => !x.startsWith("#") && x.trim.nonEmpty)
Util.infoLog(LOGGER, "*****文件加载完毕: " + filelines.take(10).mkString("#"))
filelines.foreach {
line =>
//做处理
}
}
else {
sys.error("*****文件不存在:" + filePath)
}
3.rdd写hive
写入前rdd转dataframe
import org.apache.spark.sql.Row
import org.apache.spark.sql.types.{StringType, StructField, StructType}
val outDF = sc.createDataFrame(inputDocsRDD.map(x => Row.apply(x:_*)),
StructType(INPUT_SCHEMA.map{x=> StructField(x, StringType)})).repartition(20)
//INPUT_SCHEMA为字段名array
若用方法1 ,则会需保持hive表字段与INPUT_SCHEMA一致
若用方法2,则只要列数对即可,最终根据hive表字段为准