【Spark-HDFS小文件合并】使用 Spark 实现 HDFS 小文件合并

【Spark-HDFS小文件合并】使用 Spark 实现 HDFS 小文件合并

需求描述:

1、使用 Spark 做小文件合并压缩处理。

2、实际生产中相关配置、日志、明细可以记录在 Mysql 中。

3、core-site.xml、hdfs-site.xml、hive-site.xml、yarn-site.xmlx 等文件放在项目的 resources 目录下进行认证。

4、下面的案例抽取出了主体部分的代码,具体实现时需要结合 HDFS 工具类,利用好 Mysql 做好配置、日志、以及相关明细,结合各自业务进行文件合并。

1)导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test.cn.suitcase</groupId>
    <artifactId>mergefiles</artifactId>
    <version>4.0.0</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <encoding>UTF-8</encoding>
<!--        <spark.version>3.0.2</spark.version>-->
        <spark.version>2.4.8</spark.version>
        <scala.version>2.11.12</scala.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.20.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-client -->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-hdfs -->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.20.0</version>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>

        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-compiler</artifactId>
            <version>${scala.version}</version>
        </dependency>

        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-reflect</artifactId>
            <version>${scala.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>${spark.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-launcher_2.11</artifactId>
            <version>${spark.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.11</artifactId>
            <version>${spark.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-hive_2.11</artifactId>
            <version>${spark.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.32</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.14.2</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <!-- Java Compiler -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>

            <!-- We use the maven-shade plugin to create a fat jar that contains all necessary dependencies. -->
            <!-- Change the value of <mainClass>...</mainClass> if your program entry point changes. -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <!-- Run shade goal on package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <artifactSet>
                                <excludes>
                                    <exclude>org.apache.flink:force-shading</exclude>
                                    <exclude>com.google.code.findbugs:jsr305</exclude>
                                    <exclude>org.slf4j:*</exclude>
                                    <exclude>org.apache.logging.log4j:*</exclude>
                                </excludes>
                            </artifactSet>
                            <filters>
                                <filter>
                                    <!-- Do not copy the signatures in the META-INF folder.
                                    Otherwise, this might cause SecurityExceptions when using the JAR. -->
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
                <configuration>
                    <groups>IntegrationTest</groups>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
            </plugin>
        </plugins>
    </build>

</project>

2)代码实现

2.1.HDFSUtils

public class HDFSUtils {

    private static Logger logger = LoggerFactory.getLogger(HDFSUtils.class);
    private static final Configuration hdfsConfig = new Configuration();
    private static FileSystem fs;

    public static void init() {
        System.out.println(Thread.currentThread().getContextClassLoader());
        try {
            hdfsConfig.addResource(Thread.currentThread().getContextClassLoader().getResource("./core-site.xml"));
            hdfsConfig.addResource(Thread.currentThread().getContextClassLoader().getResource("./hdfs-site.xml"));
            fs = FileSystem.get(hdfsConfig);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
            logger.error("Load properties failed.");
        } catch (IOException ioe) {
            ioe.printStackTrace();
            logger.error(String.format("IOException: " + ioe.getMessage()));
        }
    }

    public static long getDirectorySize(String directoryPath) {
        final Path path = new Path(directoryPath);
        long size = 0;
        try {
            size = fs.getContentSummary(path).getLength();


        } catch (IOException ex) {

        }
        return size;
    }

    public static long getFileCount(String directoryPath) {
        final Path path = new Path(directoryPath);
        long count = 0;
        try {
            count = fs.getContentSummary(path).getFileCount();


        } catch (IOException ex) {

        }
        return count;
    }

    public static long getBlockSize() {
        return fs.getDefaultBlockSize(fs.getHomeDirectory());
    }

    public static String getFile(String filePath) {
        final Path path = new Path(filePath);
        FSDataInputStream dis = null;
        String fileName = null;
        try {
            if (fs.exists(path) && fs.isFile(path)) {
                dis = fs.open(path);
                StringWriter stringWriter = new StringWriter();
                IOUtils.copy(dis, stringWriter, "UTF-8");
                fileName = stringWriter.toString();
                return fileName;
            } else {
                throw new FileNotFoundException();
            }
        } catch (IOException ioException) {
            logger.error("Get file from hdfs failed: " + ioException.getMessage());

        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException ex) {
                    logger.error("close FSDataInputStream failed: " + ex.getMessage());
                }
            }
        }
        return fileName;
    }

    public static Boolean exists(String filePath) {
        Path path = new Path(filePath);
        Boolean ifExists = false;
        try {
            ifExists = fs.exists(path);
            return ifExists;
        } catch (IOException ex) {
            logger.error(String.format("hdfs file %s not exists", filePath));

        }
        return ifExists;
    }

    public static boolean renameDir(String existingName, String newName) {
        final Path existingPath = new Path(existingName);
        final Path finalName = new Path(newName);
        try {
            if (exists(newName)) {
                logger.error(String.format("Path %s already exists when try to rename %s to %s.", newName, existingName, newName));
                return false;
            }
            return fs.rename(existingPath, finalName);
        } catch (IOException ex) {
            logger.error("Rename hdfs directory failed: " + ex.getMessage());
        }
        return false;
    }

    public static boolean removeDirSkipTrash(String dir) {
        Path path = new Path(dir);
        boolean rv = false;
        try {
            if (exists(dir)) {
                if (fs.delete(path, true)) {
                    logger.info(String.format("文件夹 %s 删除成功.", path));
                    rv = true;
                }
            } else {
                logger.error(String.format("要删除的文件夹 %s 不存在", dir));
                return false;
            }
        } catch (IOException ex) {
            logger.error("文件夹 %s 存在但是删除失败");
        }
        return rv;

    }

    public static List<String> listDirs(String baseDir) {
        Path path = new Path(baseDir);
        List<String> dirs = new ArrayList<>();
        try {
            FileStatus[] fileStatuses = fs.globStatus(path);

            for (int i = 0; i < fileStatuses.length; i++) {
                dirs.add(fileStatuses[i].getPath().toUri().getRawPath());
                }
            }
        } catch (Exception ex) {
            logger.error(String.format("List directories under %s failed.", baseDir));
        }
        return dirs;
    }

    public static void close() {
        try {
            fs.close();
        } catch (IOException ex) {
            logger.error("hdfs file system close failed: " + ex.getMessage());
        }
    }

}

2.2.MergeFilesApplication

下面的案例抽取出了主体部分的代码,具体实现时需要结合 HDFS 工具类,利用好 Mysql 做好配置、日志、以及相关明细,结合各自业务进行文件合并。

public class MergeFilesApplication {

    public static void main(String[] args) {
        System.out.println(Arrays.asList(args));
        //指定hadoop用户
        System.setProperty("HADOOP_USER_NAME", "hdfs");
        System.setProperty("user.name", "hdfs");
        //获取 SparkSession 对象
		SparkSession sparkSession = SparkSession.builder()
                .config("spark.scheduler.mode", "FAIR")//配置调度模式
                .config("spark.sql.warehouse.dir", "/warehouse/tablespace/external/hive")//配置warehouse目录
                .appName("MergeFilesApplication")
                .getOrCreate();
		//合并文件
        sparkSession.read()//spark读取
                    .parquet(sourceDir)//读取数据源目录
                    .coalesce(partitions)//配置spark分区数
                    .sortWithinPartitions("col1", "col2")//每个分区内按照指定需要的列进行排序
                    .write()//spark写入
                    .mode(SaveMode.Append)//写入模式为追加
                    .option("compression", "gzip")//压缩方式以为gzip
                    .parquet(targetMergedDir);//写入目标目录
    }
}
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 您好, 如果您的服务器有kerberos安全认证,那么在使用spark-sql操作hdfs文件时,需要进行以下步骤: 1. 配置kerberos认证信息:在spark的配置文件中,需要配置kerberos认证信息,包括krb5.conf文件路径、keytab文件路径、principal等信息。 2. 启用kerberos认证:在spark-submit或spark-shell命令中,需要添加--principal和--keytab参数,指定使用哪个principal和keytab文件进行认证。 3. 配置hdfs认证信息:在hdfs-site.xml文件中,需要配置hadoop.security.authentication为kerberos,并配置hadoop.security.authorization为true。 4. 配置hdfs权限:在hdfs中,需要为spark用户授权,使其能够访问hdfs文件。 完成以上步骤后,您就可以使用spark-sql操作hdfs文件了。如果您还有其他问题,请随时联系我。 ### 回答2: Spark SQL是一种可以结合HDFS文件进行操作的处理引擎,它可以很好地支持Kerberos认证,在保证数据安全的同时,可以使用HDFS文件进行处理和分析。 首先,如果服务器上安装了Kerberos安全认证,那么我们需要先在Spark SQL中配置Kerberos认证,以保证Spark SQL能够正常访问HDFS文件。具体的配置步骤如下: 1. 在Spark的conf目录下找到spark-defaults.conf文件,添加以下配置: spark.hadoop.fs.defaultFS hdfs://namenode:8020 spark.hadoop.hadoop.security.authentication kerberos spark.hadoop.hadoop.security.authorization true spark.hadoop.hadoop.security.auth_to_local "DEFAULT" spark.hadoop.hadoop.security.auth_to_local.rules "RULE:[1:$1@$0](.*@MYREALM.COM)s/@.*//DEFAULT\nRULE:[2:$1@$0](.*@MYREALM.COM)s/@.*//DEFAULT" 2.将Kerberos配置文件krb5.conf放到Spark conf目录下,并且保持与Hadoop配置文件相同。 3.将spark-submit命令添加以下参数: --jars $KRB5_LIB_PATH/krb5-1.13.2.jar,$KRB5_LIB_PATH/javax.security.auth.jar \ --principal ${kinit-user}@${REALM} --keytab ${keytab-file}.keytab 其中,$KRB5_LIB_PATH是Kerberos安装路径,${kinit-user}是Kerberos用户,${REALM}是域名称,${keytab-file}是keytab文件名称。 以上配置完成后,就可以使用Spark SQL对HDFS文件进行处理和分析了。具体的操作步骤如下: 1.创建SparkSession连接: val spark = SparkSession .builder() .appName("Spark SQL Kerberos Demo") .config("spark.sql.warehouse.dir", "$HIVE_HOME/warehouse") .enableHiveSupport() .getOrCreate() 2.加载HDFS文件: val data = spark.read.format("csv") .option("header", "true") .option("inferSchema", "true") .load("hdfs://namenode:8020/user/data/file.csv") 其中,文件路径为HDFS的绝对路径。 3.对数据进行处理: data.createOrReplaceTempView("temp_table") val result = spark.sql("SELECT COUNT(*) FROM temp_table") 其中,将数据加载到临时表中,使用SQL语句对数据进行统计处理。 4.输出结果: result.show() 以上就是使用Spark SQL操作HDFS文件的步骤和方法,并且在Kerberos认证的环境下实现数据的安全处理。通过以上的配置和步骤,我们可以很好地利用Spark SQL来分析和处理大数据,提高数据分析的效率和精度。 ### 回答3: Apache Spark是一种大数据处理框架,它可以快速高效地处理数据,包括从hdfs文件中读取和写入数据。在使用Spark进行数据处理时,很可能需要在kerberos安全认证的服务器上访问hdfs文件,因此需要进行相应的操作。 首先,要在Spark中配置kerberos的认证信息。这可以通过在spark-env.sh文件中设置相关的环境变量来实现。以下是一个示例: export HADOOP_CONF_DIR=/etc/hadoop/conf export KRB5_CONF=/etc/krb5.conf export SPARK_OPTS="--driver-java-options=-Djava.security.auth.login.config=/etc/hadoop/conf/kafka_client_jaas.conf" 这里,HADOOP_CONF_DIR指定了hadoop配置文件的路径,KRB5_CONF指定了krb5.conf的路径,SPARK_OPTS指定了Java选项的设置,通过这些设置,Spark将可以访问kerberos下的hdfs文件。 接下来,可以使用Spark SQL来读取和写入hdfs文件。在Spark中,可以使用SparkSession创建一个SQLContext对象,该对象允许使用Spark SQL来查询和处理数据。以下是一个简单的例子: from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("Read and Write from kerberos") \ .getOrCreate() # 读取hdfs文件 data = spark.read.parquet("hdfs://<namenode>/<file-path>") # 进行数据处理和转换 # 写入hdfs文件 data.write.parquet("hdfs://<namenode>/<file-path>") 这里,`SparkSession.builder`用于创建一个SparkSession对象,并指定应用程序名称。使用`spark.read`方法可以让SparkSQL从hdfs中读取数据,使用`data.write`方法可以将处理后的数据写回到hdfs中。 总的来说,通过Spark SQL,我们可以方便地操作hdfs文件,而通过设置kerberos认证信息,我们可以在安全的环境下进行数据处理和存储。这使得Spark大数据处理方面具有非常广泛的应用前景。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值