若Spark读取HDFS文件夹时, 其中的小文件过多会降低程序性能,也给HDFS带来压力。
当Spark读取文件时, 会为每个文件的数据分配一个Partition, 可以使用coalesce
算子减少rdd中的分区。
- 首先, 编写函数实现根据文件大小来确定分区数的功能
def coalesceNum(path: String, targetSize_M: Long): Int ={
val fileSystem = FileSystem.get(new URI("hdfs://c1:8020"),new Configuration(), "hdfs");
var size = 0l
fileSystem.globStatus(new Path(path + "/*")).foreach(x => {
size += x.getLen
})
// 加一是因为Partition的个数不能为0
(size / 1024 /1024 / size).toInt + 1
}
- 使用
coalesce
算子
val originRDD = spark.sparkContext.textFile(path).coalesce(RddUtils.coalesceNum(path, 20))