大数据问题排查系列 - HDFS FileSystem API 的正确打开方式,你 GET 了吗?

简介: 大数据问题排查系列 - HDFS FileSystem API 的正确打开方式,你 GET 了吗?

前言

大家好,我是明哥!

本片博文是“大数据问题排查系列”之一,我们首先会聊聊一个问题的现象原因和解决方法,然后给出 HDFS FileSystem API 常见的两种使用方式,最后来看下 HDFS 源码中是如何根据用户的配置文件创建对应的 FileSystem 对象实例的。

以下是正文。

从一个报错聊起

  • 问题现象:某 JAVA 作业需要读取 HDFS 文件系统中的文件,作业提交后报错如下:
java.io.IOException: No FileSystem for scheme: hdfs
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2584)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
  • 问题原因:类加载路径上缺少 hdfs 相关 Jar包 hadoop-hdfs-*.jar,导致org.apache.hadoop.fs.FileSystem 创建 FileSystem实列 时没有创建 org.apache.hadoop.hdfs.DistributedFileSystem,所以当配置文件中配置 fs.defaultFS 为 hdfs://nameservice1 时,会寻找 hdfs scheme 即org.apache.hadoop.hdfs.DistributedFileSystem,此时自然找不到,就会报上述错误。
  • 问题解决:只需要确保类的 Classpath 下有对应的 hdfs相关 jar报即可解决上述报错(注意在分布式环境中可能会涉及到不同 classloader下不同的加载机制),具体来讲:
  1. 可以在 pom中添加相关依赖:
<dependency>
        <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>2.7.4</version>
        </dependency>
  1. 在linux上提交时,可以通过类似以下命令确保类加载路径上包含相关 hdfs jar包:
java -cp ./test-1.0-SNAPSHOT-jar-with-dependencies.jar:`hadoop classpath` com.hundsun.HdfsTest core-site-test.xml hdfs-site-test.xml

HDFS FileSystem api 常见的两种方式

粗略来看,通过 HDFS FileSystem api 创建 FileSystem 实例时,主要有两种方式,两者在如何配置访问不同集群的 HDFS 上略有差异。以下是示例代码。

  1. 方式一:代码使用原生JAVA,目标 hdfs 集群的配置信息,通过导出目标集群中的配置文件core-site 和 hdfs-site.xml并放到特定路径下加载进来
package com.mingge.hdfs.demo;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.IOException;
public class HdfsTest {
    /**
     *
     1. If there are configuration files in the classpath with default names like core-site.xml, hdfs-site.xml,
     The Configuration class will automatically load them;
     2. If your configuration files are not following the default names like core-site.xml, hdfs-site.xml,
     you must load them explicitly;
     3. If the configuration files are already in the classpath, you can load them this way:
     conf.addResource(Thread.currentThread().getContextClassLoader().getResourceAsStream(coreConfPath));
     4. If the configuration files are not in the classpath, you can load them this way:
     conf.addResource(new Path(coreConfPath));
     */
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        // paths to configuration files
        String coreConfPath = null;
        String hdfsConfPath = null;
        coreConfPath = args[0];
        hdfsConfPath = args[1];
        // you can use absolute paths, like below on windows:
//        coreConfPath = "E:\\git\\test\\src\\main\\resources\\core-site-test.xml";
//        hdfsConfPath = "E:\\git\\test\\src\\main\\resources\\hdfs-site-test.xml";
        // If you use relative paths, the files must be in the cwd, which can be get by System.getProperty("user.dir");
//        coreConfPath = "core-site-test.xml";
//        hdfsConfPath = "hdfs-site-test.xml";
//        conf.addResource(new Path(coreConfPath));
//        conf.addResource(new Path(hdfsConfPath));
        // if the configuraton files are already in the classpath, you can also use below codes to load them:
        conf.addResource(Thread.currentThread().getContextClassLoader().getResourceAsStream(coreConfPath));
        conf.addResource(Thread.currentThread().getContextClassLoader().getResourceAsStream(hdfsConfPath));
//        System.getenv().forEach((key,value) -> System.out.println(key.toString() + value.toString()));
//        System.getProperties().forEach((key,value) -> System.out.println(key.toString() + value.toString()));
//        conf.iterator().forEachRemaining((confItem)-> System.out.println(confItem.toString()));
        System.out.println("user dir is: " + System.getProperty("user.dir"));
        try { FileSystem fileSystem = FileSystem.get(conf);
        for (FileStatus status: fileSystem.listStatus(new Path("/"))){
            System.out.println(status.getPath());}
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 方式二:代码使用 spring 框架,目标HDFS 集群相关配置信息,配置在 properties 配置文件中:
package com.mingge.hdfs.demo;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
/**
 * Created by xxx on xxx.
 */
@Configuration
public class HdfsConfig {
    private final Logger log = Logger.getLogger(this.getClass());
    @Value("${fs.default.name}")
    String fs_default_name;
    @Value("${fs.namenode.isha:false}")
    boolean fs_namenode_isha;
    @Value("${fs.namenode.address:}")
    private String fs_namenode_address;
    @Value("${hadoop.security.authentication:}")
    String hadoop_auth;
    @Value("${key.user:}")
    String key_user;
    @Value("${key.path:}")
    String key_path;
    @Value("${java.security.krb5.conf:}")
    String kbr5_conf;
    @Value("${dfs.namenode.kerberos.principal:}")
    String dfs_namenode_kerberos_principal;
    @Bean(name = "configuration1")
    public org.apache.hadoop.hdfs.HdfsConfiguration configuration(){
        org.apache.hadoop.hdfs.HdfsConfiguration conf = new HdfsConfiguration();
        if(fs_namenode_isha){
            String clusterName = "clusterName";
            conf.set("fs.defaultFS", fs_default_name);
            conf.set("dfs.nameservices", clusterName);
            if(StringUtils.isBlank(fs_namenode_address)){
                throw new RuntimeException("fs.namenode.address 不能为空");
            }
            int i = 0;
            StringBuilder nodes = new StringBuilder();
            for(String address : fs_namenode_address.split(",")){
                i++;
                nodes.append(",nn").append(i);
                conf.set("dfs.namenode.rpc-address."+clusterName+".nn" + i, address);
            }
            conf.set("dfs.ha.namenodes."+clusterName, nodes.substring(1));
            //conf.setBoolean(name, value);
            conf.set("dfs.client.failover.proxy.provider."+clusterName,
                    "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        }else{
            conf.set("fs.default.name",fs_default_name);
        }
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        if (StringUtils.isNotBlank(kbr5_conf)) {
//            System.setProperty("HADOOP_USER_NAME", user); //设置当前window/linux下用户为HBase可访问用户
            System.setProperty("java.security.krb5.conf", kbr5_conf );
            /** 使用Hadoop安全登录 **/
            conf.set("hadoop.security.authentication", hadoop_auth);
            conf.set("dfs.namenode.kerberos.principal", dfs_namenode_kerberos_principal);
            try {
                UserGroupInformation.setConfiguration(conf);
                UserGroupInformation.loginUserFromKeytab(key_user, key_path);
                log.info("=========================kerberos登录成功==============================");
            } catch (IOException e1) {
                log.error("=====================登录错误==================:",e1);
                e1.printStackTrace();
            }
        }
        return conf;
    }
}

HDFS 源码中是如何根据用户的配置文件创建对应的 FileSystem 对象实例的?

通过以上方法一的代码,我们不难发现,只要在类的加载路径上有配置文件core-site.xml和hdfs-site.xml,两行简单的如下语句就可以创建好指向目标 hdfs 集群的 FileSystem对象实例:

Configuration conf = new Configuration();
FileSystem fileSystem = FileSystem.get(conf);

这背后的原理,其实涉及到源码中类 org.apache.hadoop.conf.Configuration 和 org.apache.hadoop.hdfs.HdfsConfiguration,尤其是其如下静态代码块,截图如下:

image.png

Configuration.java

image.png

HdfsConfiguration.java

相关知识点,总结如下:

  • If there are configuration files in the classpath with default names like core-site.xml, hdfs-site.xml, the Configuration class will automatically load them;
  • If your configuration files are not following the default names like core-site.xml, hdfs-site.xml, you must load them explicitly;
  • If the configuration files are already in the classpath, you can load them this way: conf.addResource(Thread.currentThread().getContextClassLoader().getResourceAsStream(coreConfPath));
  • If the configuration files are not in the classpath, you can load them this way: conf.addResource(new Path(coreConfPath));

大家可以在 IDE 工具中导入以上方法一的代码,DEBUG 调试下以了解其中的细节。以下是笔者排查上述问题时,debug过程中的相关截图:

image.png

debug FileSystem.java when no org.apache.hadoop:hadoop-hdfs is in the classpath


image.png

debug FileSystem.java when org.apache.hadoop:hadoop-hdfs is in the classpath


相关实践学习
基于MaxCompute的热门话题分析
Apsara Clouder大数据专项技能认证配套课程:基于MaxCompute的热门话题分析
相关文章
|
6天前
|
存储 弹性计算 缓存
阿里云服务器租赁费用:新版租赁收费标准及活动报价参考
本文更新了2026年阿里云全系列云服务器租赁活动报价,所有特惠资源均可前往阿里云活动中心选购,整体覆盖从个人入门到企业级高性能场景的全梯度需求。其中轻量应用服务器主打极致性价比,2核2G峰值200M带宽配置每日10点、15点限时抢购价仅38元/年,2核4G配置379元/年起;高性价比的经济型e实例、通用算力型u2i实例覆盖2核4G至4核32G全档位,适配开发测试与中小型企业业务;搭载英特尔至强6处理器的第九代c9i企业级实例算力较上代提升20%,支撑高并发生产环境,不同实例规格价差清晰,用户可根据自身业务负载与预算灵活选型。
1628 116
|
7天前
|
人工智能 程序员 API
Codex 接入 DeepSeek-V4-Flash:还能补上识图,提供两套方案
Codex 接入 DeepSeek-V4-Flash 怎么配?本文覆盖 CLI 与桌面端,再用 qwen3-vl-flash 补识图,两套方案可直接照做
1105 5
|
13天前
|
云安全 人工智能 运维
阿里云联动百位企业安全专家,共识Agent防御最佳实践
当Agent成为新员工,你的安全边界在哪里?
1954 9
阿里云联动百位企业安全专家,共识Agent防御最佳实践
|
7天前
|
编解码 人工智能 安全
2核4G/4核8G/8核16G阿里云服务器如何选择实例?经济型e、通用算力型u2i与计算型c9i选哪个?
本文介绍了阿里云2核4G、4核8G、8核16G三档主流配置下经济型e、通用算力型u2i和计算型c9i三种实例的最新活动价格与适用场景。同配置下三者价差显著,以2核4G为例,经济型e低至599.93元/年,计算型c9i则高达1742.08元/年。文章详细解析了各实例的性能定位:经济型e适合轻负载入门场景,u2i兼顾稳定算力与性价比,c9i凭借第9代至强处理器与芯片级安全能力支撑高性能业务。同时提示用户可叠加满减优惠券享受折上折,建议根据业务负载与预算综合决策。
538 112
|
19天前
|
人工智能 前端开发 Linux
Codex 桌面版安装 + CC Switch 接入第三方 API 完整教程(2026 最新)
2026最新教程:手把手教你安装Codex桌面版,通过CC Switch v3.17.0一键接入Fenno等国产API(兼容OpenAI Responses格式),跳过账号登录,完整启用代码审查、多步任务与上下文感知功能。零基础友好,全程图文实操。(239字)
2749 4
|
11天前
|
存储 人工智能 关系型数据库
阿里云AI产品与云产品最新组合套餐:Token Plan、AI coding及云服务器和建站等组合优惠价
阿里云推出全新“算力+模型+应用”一站式云与AI组合套餐活动,覆盖从个人开发者到中大型企业的全场景需求。核心亮点为分三档定价的Token Plan订阅服务,支持Qwen3.8-Max-Preview大模型调用,错峰时段最低可享0.2折优惠。活动同步推出AI Coding、智能体部署、云电脑托管、0代码建站等十余类场景化组合,搭配99元/年的普惠云服务器、88元/年的入门数据库等经典特惠产品,还为企业提供1V1定制化AI转型方案,大幅降低了不同用户群体拥抱AI的技术门槛与采购成本。
730 111
|
21天前
|
人工智能 JSON 安全
Fastjson远程代码执行漏洞,阿里云AI安全为您保驾护航
阿里云AI安全产品联动防御Fastjson攻击
2653 13
Fastjson远程代码执行漏洞,阿里云AI安全为您保驾护航
|
7天前
|
人工智能 JSON Shell
2026AI漫剧本地全开源方案(附各个软件模型链接),8G显卡也能流畅运行
这是一套完全本地化部署的AI漫剧生成技术链路:涵盖LLM剧本分镜生成、FLUX文生图(IP-Adapter人脸锁定)、StoryDiffusion时序连贯控制、LTX-2.3唇形同步视频生成,及ComfyUI全流程调度。零云端费用,仅耗硬件算力,单集2–4小时可产出竖屏短视频,适配抖音/B站分发。
|
5天前
|
人工智能 API 开发工具
2026 零基础本地 AI 漫剧完整实操教程(8G 笔记本显卡可用|附可直接复制命令与代码)
本方案提供完全离线、本地运行的漫剧全自动制作流程:RTX3060/4050 8G显卡即可驱动,涵盖Qwen写分镜→ComfyUI统一角色绘图→LTX2.3图生微动画→Qwen3-TTS本地配音→FFmpeg自动合成,全程无水印、免API、不限次。专为低显存优化,解决变脸、闪烁、爆内存三大痛点。(239字)

热门文章

最新文章