Hadoop_HDFS笔记2(HDFS的API操作,HDFS的读写流程(面试重点))

一、HDFS的API操作

1、客户端环境准备

1)找到资料包路径下的Windows依赖文件夹,拷贝hadoop-3.1.0到非中文路径(比如d:\)。
2)配置HADOOP_HOME环境变量
在这里插入图片描述
3)配置Path环境变量。
注意:如果环境变量不起作用,可以重启电脑试试。
在这里插入图片描述
验证Hadoop环境变量是否正常。双击winutils.exe,如果报如下错误。说明缺少微软运行库(正版系统往往有这个问题)。再资料包里面有对应的微软运行库安装包双击安装即可。
在这里插入图片描述
4)在IDEA中创建一个Maven工程HdfsClientDemo,并导入相应的依赖坐标+日志添加

<dependencies>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>3.1.3</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
    </dependency>
</dependencies>

在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”,在文件中填入

log4j.rootLogger=INFO, stdout  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  
log4j.appender.logfile=org.apache.log4j.FileAppender  
log4j.appender.logfile.File=target/spring.log  
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout  
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

5)创建包名:com.atguigu.hdfs
6)创建HdfsClient类

public class HdfsClient {

    @Test
    public void testMkdirs() throws IOException, URISyntaxException, InterruptedException {

        // 1 获取文件系统
        Configuration configuration = new Configuration();

        // FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration);
        FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration,"atguigu");

        // 2 创建目录
        fs.mkdirs(new Path("/xiyou/huaguoshan/"));

        // 3 关闭资源
        fs.close();
    }
}

7)执行程序
客户端去操作HDFS时,是有一个用户身份的。默认情况下,HDFS客户端API会从采用Windows默认用户访问HDFS,会报权限异常错误。所以在访问HDFS时,一定要配置用户。

org.apache.hadoop.security.AccessControlException: Permission denied: user=56576, access=WRITE, inode="/xiyou/huaguoshan":lyh:supergroup:drwxr-xr-x

2、HDFS的API案例实操

(1)HDFS文件上传(测试参数优先级)

1)编写源代码

@Test
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    configuration.set("dfs.replication", "2");
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "lyh");

    // 2 上传文件
    fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/xiyou/huaguoshan"));

    // 3 关闭资源
    fs.close();

2)将hdfs-site.xml拷贝到项目的resources资源目录下

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
	<property>
		<name>dfs.replication</name>
         <value>1</value>
	</property>
</configuration>

3)参数优先级
参数优先级排序:(1)客户端代码中设置的值 >(2)ClassPath下的用户自定义配置文件 >(3)然后是服务器的自定义配置(xxx-site.xml) >(4)服务器的默认配置(xxx-default.xml)

(2)HDFS文件下载

@Test
public void testCopyToLocalFile() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "lyh");
    
    // 2 执行下载操作
    // boolean delSrc 指是否将原文件删除
    // Path src 指要下载的文件路径
    // Path dst 指将文件下载到的路径
    // boolean useRawLocalFileSystem 是否开启文件校验
    fs.copyToLocalFile(false, new Path("/xiyou/huaguoshan/sunwukong.txt"), new Path("d:/sunwukong2.txt"), true);
    
    // 3 关闭资源
    fs.close();
}

(3) HDFS文件更名和移动

@Test
public void testRename() throws IOException, InterruptedException, URISyntaxException{

	// 1 获取文件系统
	Configuration configuration = new Configuration();
	FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "lyh"); 
		
	// 2 修改文件名称
	fs.rename(new Path("/xiyou/huaguoshan/sunwukong.txt"), new Path("/xiyou/huaguoshan/meihouwang.txt"));
		
	// 3 关闭资源
	fs.close();
}

(4)HDFS删除文件和目录

@Test
public void testDelete() throws IOException, InterruptedException, URISyntaxException{

	// 1 获取文件系统
	Configuration configuration = new Configuration();
	FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "lyh");
		
	// 2 执行删除
	fs.delete(new Path("/xiyou"), true);
		
	// 3 关闭资源
	fs.close();
}

(5)HDFS文件详情查看

  • 查看文件名称、权限、长度、块信息
@Test
public void testListFiles() throws IOException, InterruptedException, URISyntaxException {

	// 1获取文件系统
	Configuration configuration = new Configuration();
	FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "lyh");

	// 2 获取文件详情
	RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);

	while (listFiles.hasNext()) {
		LocatedFileStatus fileStatus = listFiles.next();

		System.out.println("========" + fileStatus.getPath() + "=========");
		System.out.println(fileStatus.getPermission());
		System.out.println(fileStatus.getOwner());
		System.out.println(fileStatus.getGroup());
		System.out.println(fileStatus.getLen());
		System.out.println(fileStatus.getModificationTime());
		System.out.println(fileStatus.getReplication());
		System.out.println(fileStatus.getBlockSize());
		System.out.println(fileStatus.getPath().getName());

		// 获取块信息
		BlockLocation[] blockLocations = fileStatus.getBlockLocations();
		System.out.println(Arrays.toString(blockLocations));
	}
	// 3 关闭资源
	fs.close();
}

(6)HDFS文件和文件夹判断

@Test
public void testListStatus() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件配置信息
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "lyh");

    // 2 判断是文件还是文件夹
    FileStatus[] listStatus = fs.listStatus(new Path("/"));

    for (FileStatus fileStatus : listStatus) {

        // 如果是文件
        if (fileStatus.isFile()) {
            System.out.println("f:"+fileStatus.getPath().getName());
        }else {
            System.out.println("d:"+fileStatus.getPath().getName());
        }
    }

    // 3 关闭资源
    fs.close();
}

(7)将上述的代码全部合并在一起

package com.lyh.hdfs;

import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.ls.LSOutput;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;

/*
/客户端常用代码套路
1、获取一个客户端对象
2、执行相关的操作命令
3、关闭资源
 */
public class HdfsClient {

    private FileSystem fs;

    @Before
    public void init() throws URISyntaxException, IOException, InterruptedException {
        //连接的集群nn地址
        URI uri = new URI("hdfs://hadoop102:8020");
        //创建一个配置文件
        Configuration configuration = new Configuration();
        configuration.set("dfs.replication", "2");

        //用户
        String user = "lyh";
        //1、获取到了客户端对象
        fs = FileSystem.get(uri, configuration, user);
    }

    @After
    public void close() throws IOException {
        //3、关闭资源
        fs.close();
    }

    //创建目录
    @Test
    public void testMkdir() throws URISyntaxException, IOException, InterruptedException {

        //2、创建一个文件夹
        fs.mkdirs(new Path("/xiyou/huaguoshan1"));
    }


    //上传
    //参数优先级:hdfs-default.xml=>hdfs-site.xml=>在项目资源目录下的配置文件=>代码里的配置
    @Test
    public void testPut() throws IOException {
        //参数:参数一:表示删除数据,参数二:表示是否允许覆盖,参数三:原数据路径,参数四:目的地路径
        fs.copyFromLocalFile(false, false, new Path("D:\\sunwukong.txt"),
                new Path("hdfs://hadoop102/xiyou/huaguoshan"));
    }


    //文件下载
    @Test
    public void testGet() throws IOException {
        //参数一:原文件是否删除,参数二:源文件路径hdfs,参数三:目标地址路径windows,参数四:有无crc文件
        fs.copyToLocalFile(false, new Path("hdfs://hadoop102/xiyou/huaguoshan"),
                new Path("D:\\"), false);

    }

    //删除
    @Test
    public void testRm() throws IOException {
        //参数一:要删除的路径,参数二:是否递归删除
        //删除文件
        //fs.delete(new Path("/jdk-8u333-linux-x64.tar.gz"),false);


        //删除空目录
        //fs.delete(new Path("/xiyou"),false);

        //删除非空目录
        fs.delete(new Path("/jinguo"), true);

    }


    //文件的更名和移动
    @Test
    public void testMv() throws IOException {
        //参数一:原文件路径,参数二:目标文件路径
        //文件名称修改
        fs.rename(new Path("/input/word.txt"), new Path("/inout/ss.txt"));

        //文件的移动和更名
        fs.rename(new Path("/input/ss.txt"), new Path("/cls.txt"));

        //目录更名
        fs.rename(new Path("/input"), new Path("/output"));
    }


    //获取文件详细信息
    @Test
    public void fileDetail() throws IOException {
        //获取所有文件信息
        RemoteIterator<LocatedFileStatus> listFiles =
                fs.listFiles(new Path("/"), true);
        //遍历文件
        while (listFiles.hasNext()) {
            LocatedFileStatus fileStatus = listFiles.next();

            System.out.println("========" + fileStatus.getPath() + "==========");

            System.out.println(fileStatus.getPermission());

            System.out.println(fileStatus.getOwner());

            System.out.println(fileStatus.getGroup());

            System.out.println(fileStatus.getLen());

            System.out.println(fileStatus.getModificationTime());

            System.out.println(fileStatus.getReplication());

            System.out.println(fileStatus.getBlockSize());

            System.out.println(fileStatus.getPath().getName());

            //获取块信息
            BlockLocation[] blockLocations = fileStatus.getBlockLocations();
            System.out.println(Arrays.toString(blockLocations));

        }
    }

        //判断是文件还是文件夹
        @Test
        public void testFile() throws IOException{
            FileStatus[] listStatus = fs.listStatus(new Path("/"));
            for (FileStatus status : listStatus) {
                if (status.isFile()) {
                    System.out.println("文件"+status.getPath().getName());
                }else{
                    System.out.println("目录"+status.getPath().getName());
                }
            }

        }

    }




二、HDFS的读写流程(面试重点)

1、HDFS写数据流程

(1)剖析文件写入

在这里插入图片描述
(1)客户端通过Distributed FileSystem模块向NameNode请求上传文件,NameNode检查目标文件是否已存在,父目录是否存在。
(2)NameNode返回是否可以上传。
(3)客户端请求第一个 Block上传到哪几个DataNode服务器上。
(4)NameNode返回3个DataNode节点,分别为dn1、dn2、dn3。
(5)客户端通过FSDataOutputStream模块请求dn1上传数据,dn1收到请求会继续调用dn2,然后dn2调用dn3,将这个通信管道建立完成。
(6)dn1、dn2、dn3逐级应答客户端。
(7)客户端开始往dn1上传第一个Block(先从磁盘读取数据放到一个本地内存缓存),以Packet为单位,dn1收到一个Packet就会传给dn2,dn2传给dn3;dn1每传一个packet会放入一个应答队列等待应答。
(8)当一个Block传输完成之后,客户端再次请求NameNode上传第二个Block的服务器。(重复执行3-7步)。

(2)网络拓扑-节点距离计算

  • 在HDFS写数据的过程中,NameNode会选择距离待上传数据最近距离的DataNode接收数据。那么这个最近距离怎么计算呢?
  • 节点距离:两个节点到达最近的共同祖先的距离总和
    在这里插入图片描述
    例如,假设有数据中心d1机架r1中的节点n1。该节点可以表示为/d1/r1/n1。利用这种标记,这里给出四种距离描述。

大家算一算每两个节点之间的距离。
在这里插入图片描述

(3)机架感知(副本存储节点选择)

1)机架感知说明
(1)官方说明(网址)
http://hadoop.apache.org/docs/r3.1.3/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html#Data_Replication

For the common case, when the replication factor is three, HDFS’s
placement policy is to put one replica on the local machine if the
writer is on a datanode, otherwise on a random datanode, another
replica on a node in a different (remote) rack, and the last on a
different node in the same remote rack. This policy cuts the
inter-rack write traffic which generally improves write performance.
The chance of rack failure is far less than that of node failure; this
policy does not impact data reliability and availability guarantees.
However, it does reduce the aggregate network bandwidth used when
reading data since a block is placed in only two unique racks rather
than three. With this policy, the replicas of a file do not evenly
distribute across the racks. One third of replicas are on one node,
two thirds of replicas are on one rack, and the other third are evenly
distributed across the remaining racks. This policy improves write
performance without compromising data reliability or read performance.

(2)源码说明
在idea中Crtl + n 查找BlockPlacementPolicyDefault,在该类中查找chooseTargetInOrder方法。

如果找不到方法,需要在pom.xml中加入依赖
在这里插入图片描述

2)Hadoop3.1.3副本节点选择
在这里插入图片描述

2、HDFS读数据流程

在这里插入图片描述
(1)客户端通过DistributedFileSystem向NameNode请求下载文件,NameNode通过查询元数据,找到文件块所在的DataNode地址。
(2)挑选一台DataNode(就近原则,然后随机)服务器,请求读取数据。
(3)DataNode开始传输数据给客户端(从磁盘里面读取数据输入流,以Packet为单位来做校验)。
(4)客户端以Packet为单位接收,先在本地缓存,然后写入目标文件。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值