java API访问hadoop(含HA)--FileSystem

博客介绍了使用Hadoop访问HDFS集群的两种模式。非HA模式下,直接在URI中写明hdfs地址;HA模式下,使用Hadoop Java API访问时,创建FileSystem对象需指定NameSpace和主备NameNode的IP及端口等信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录

1 非HA

直接在URI中写明hdfs地址即可。如:

    static FileSystem fs;

    static {
        try {
            fs = FileSystem.get(new URI("hdfs://cluster-host1:9000"),new Configuration(),"hadoop");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void mkdir() throws IOException {
        String path = "/test/fs";
        fs.mkdirs(new Path(path),new FsPermission("755"));//绝对路径,相对路径会在每个用户下
    }
    public static void listFiles(String dirName)throws IOException {
        Path f = new Path(dirName);
        FileStatus[] status =fs.listStatus(f);
        System.out.println(dirName +" has all files:");
        for (int i = 0; i<status.length; i++) {
            System.out.println(status[i].getPath().toString());
            System.out.print("  | 是否目录:"+status[i].isDirectory());
            System.out.print("  | 是否文件:"+status[i].isFile());
            System.out.print("  | permission:"+status[i].getPermission());
            System.out.print("  | owner:"+status[i].getOwner());
            System.out.println();
        }
    }
    

2 HA

在使用Hadoop Java API访问HDFS集群时,在创建FileSystem对象时,直接指定NameNode的IP以及端口号即可。但是在HA模式下,访问HDFS集群却有一些不同,需要指定NameSpace和主备NameNode的IP以及端口等信息,具体操作方式见如下代码:

public class FileSystemHA {

    //方式一:这种方式测试通过
    @Test
    public void test1() throws Exception{
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hadoop-ns1");//nameservices地址
        conf.set("dfs.nameservices", "hadoop-ns1");
        conf.set("dfs.ha.namenodes.hadoop-ns1", "nn1,nn2");
        conf.set("dfs.namenode.rpc-address.hadoop-ns1.nn1", "hadoop-master1:8020");
        conf.set("dfs.namenode.rpc-address.hadoop-ns1.nn2", "hadoop-master2:8020");
        conf.set("dfs.client.failover.proxy.provider.ns1", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        FileSystem fs = FileSystem.get(URI.create("hdfs://hadoop-ns1"), conf, "hadoop");

        String dirName = "/";
        Path f = new Path(dirName);
        FileStatus[] status =fs.listStatus(f);
        System.out.println(dirName +" has all files:");
        for (int i = 0; i<status.length; i++) {
            System.out.println(status[i].getPath().toString());
            System.out.print("  | 是否目录:"+status[i].isDirectory());
            System.out.print("  | 是否文件:"+status[i].isFile());
            System.out.print("  | permission:"+status[i].getPermission());
            System.out.print("  | owner:"+status[i].getOwner());
            System.out.println();
        }
    }

    //方式二:这种方式ok了。配置文件是从hadoop-master1上复制的
    //有用的配置参考方式一的k-v
    @Test
    public void test2() throws Exception{
        Configuration conf = new Configuration();
        conf.addResource(new Path("core-site.xml"));
        conf.addResource(new Path("hdfs-site.xml"));
        FileSystem fs = FileSystem.get(conf);
        String dirName = "/";
        Path f = new Path(dirName);
        FileStatus[] status =fs.listStatus(f);
        System.out.println(dirName +" has all files:");
        for (int i = 0; i<status.length; i++) {
            System.out.println(status[i].getPath().toString());
            System.out.print("  | 是否目录:"+status[i].isDirectory());
            System.out.print("  | 是否文件:"+status[i].isFile());
            System.out.print("  | permission:"+status[i].getPermission());
            System.out.print("  | owner:"+status[i].getOwner());
            System.out.println();
        }
    }

}
<think>我们被要求用中文回答,并且按照给定的格式要求(行内数学表达式用$...$,独立公式用$$...$$,但这里可能不涉及数学公式)。同时需要生成相关问题,并在回答中引用时添加引用标识。用户的问题:如何用JavaAPI操作HDFS获取Configuration或FileSystem客户端对象,以及Hadoop1/2/3版本是否需要启动。根据提供的引用,我们可以总结如下:引用[1]展示了一个示例:通过Configuration对象设置HDFS的URL,然后通过FileSystem.get(conf)获取FileSystem对象。同时设置了系统属性HADOOP_USER_NAME来指定用户身份。引用[2]展示了另一种方式:通过URI和Configuration对象,以及用户名来获取FileSystem对象。引用[3][4][5]提供了一些额外的信息,包括在Windows环境下需要额外的本地库(hadoop.dll和winutils.exe),以及Maven依赖的配置。关于Hadoop版本是否需要启动:-要操作HDFS,Hadoop集群必须处于运行状态。无论是1.x、2.x还是3.x版本,都需要启动HDFS服务(如NameNode和DataNode)。客户端程序通过RPC与这些服务通信。步骤总结:1.创建Configuration对象,并设置HDFS的地址(fs.defaultFS)。2.如果需要指定用户,可以设置系统属性(System.setProperty)或通过FileSystem.get的第三个参数传递。3.通过FileSystem.get方法获取FileSystem实例。注意事项:-在Windows本地开发时,需要配置hadoop.dll和winutils.exe(引用[4]),否则可能会报错。-需要添加Hadoop客户端依赖(引用[5]给出了一个依赖示例,但实际应该是hadoop-client)。下面我们按照要求组织回答:</think>### 如何用Java API操作HDFS获取客户端对象 #### 一、获取Configuration和FileSystem对象的步骤 1. **创建Configuration对象** 通过`Configuration`设置HDFS的访问地址(核心参数`fs.defaultFS`): ```java Configuration conf = new Configuration(); conf.set("fs.defaultFS", "hdfs://NameNode地址:端口"); // 例如 hdfs://hadoop00:9000 ``` 2. **身份认证(可选但推荐)** **方式1**:设置系统属性(需在`FileSystem.get`调用前执行): ```java System.setProperty("HADOOP_USER_NAME", "用户名"); // 如"root" ``` **方式2**:通过`FileSystem.get`直接传递用户: ```java FileSystem fs = FileSystem.get(uri, conf, "用户名"); ``` 3. **获取FileSystem对象** **方法1**(最常用): ```java FileSystem fs = FileSystem.get(conf); ``` **方法2**(显式指定URI): ```java URI uri = new URI("hdfs://hadoop00:9000"); FileSystem fs = FileSystem.get(uri, conf); ``` #### 二、Hadoop 1/2/3版本是否需要启动集群? - **必须启动HDFS服务** 无论Hadoop 1.x, 2.x 或 3.x,**客户端API操作前必须启动HDFS集群**(包括NameNode和DataNode)。未启动时调用API会抛出连接异常[^1][^2]。 - **特殊说明** - Hadoop 3.x在Windows本地调试时需额外配置`hadoop.dll`和`winutils.exe`[^4]。 - Hadoop 2.x/3.x推荐使用`HA`(高可用)地址,例如:`hdfs://mycluster`。 #### 三、完整代码示例 ```java import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import java.net.URI; public class HDFSClient { public static void main(String[] args) throws Exception { // 1. 创建配置对象 Configuration conf = new Configuration(); conf.set("fs.defaultFS", "hdfs://hadoop00:9000"); // 2. 设置用户身份(推荐) System.setProperty("HADOOP_USER_NAME", "root"); // 3. 获取FileSystem客户端 FileSystem fs = FileSystem.get(conf); System.out.println("HDFS连接状态: " + fs.isFile(new Path("/"))); // 验证连接 fs.close(); // 关闭资源 } } ``` #### 四、依赖配置(Maven) ```xml <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-client</artifactId> <version>3.3.6</version> <!-- 版本需匹配集群 --> </dependency> ``` > **关键提示**: > - 操作前确保集群处于`active`状态(可通过`hdfs dfsadmin -report`验证)[^1][^2] > - 客户端与集群的Hadoop版本需一致,避免兼容性问题[^4] > - 路径权限错误时抛出`AccessControlException`,需检查用户权限[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值