前面了解了hadoop写文件,读文件的执行过程,那么hadoop内部是怎么实现的呢?接下来看一下从hdfs中读取文件的源码,一起来分析一下,这样就会更加了解hdfs
首先将hadoop/share/common中的jar以及所依赖的lib中的jar,hadoop/share/hdfs中的jar以及所依赖的lib中的jar,导入到工程

总共59个jar包,写一个测试类
package cn.xmf.haddop;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Administrator on 2018/4/11.
*/
public class hdfs {
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS","hdfs://my01:9000/");
FileSystem fs = FileSystem.get(conf);
FSDataInputStream input = fs.open(new Path("/jdk-8u161-linux-x64.tar.gz"));
FileOutputStream output = new FileOutputStream("d:/jdk8.tgz");
IOUtils.copy(input,output);
}
}
运行之后,会将之前hdfs根路径下的jdk下载到d盘,效果如下图

接下来重点来了将断点打到FileSystem这一行,进入到FilegeSystem的get方法中

继续点击get,进去

向下走,会走到

可以看出三目运算,执行CACHE.get(uri,conf),那么进入到这个里面看看

Cache是FileSystem的内部类,再往下看

继续走

这里就是根据scheme从SERVICE_FILE_SYSTEMS这个里面拿出class,那么hdfs对应对FileSystem的实例是什么,继续看一下

是DistributedFileSystem终于获得了,下面就很简单,就是将这个class返回,那么在获取FileSystem的时候,其实是根据conf中配置的fs.defaultFS来确定的哪一种FileSystem。OK到这里刚才第一句话的原理才分析透彻,哪一句话呢?

就是图上的这一句话:
FileSystem fs = FileSystem.get(conf);
好了!到这里先暂停一下,说一下这个FileSystem都有哪些实现类,刚才的DistributedFileSystem看名字的意思就是分布式文件系统,说白了就是hdfs的文件系统,问什么它在命名的时候不叫HdfsFileSystem呢?原因就是:他愿意,哈哈,你能咋地,如果这个是你开发的,你可以叫HdfsFileSystem,但是你不是,我也不是,说这么多就是要记住DistributedFileSystem是HDFS的FileSystem。好了!看一下FileSystem都有哪些实现类

这一张图说明他有本地文件系统,Ftp文件系统等等
继续

从上图可以看出通过class反射出Fs,因为反射出来的是成员变量都是空的,所以要进行初始化,进入初始分方法

进入到DFSClient中

DFSClient中有一个属性叫做namenode,这个就是客户端的代理,继续跟踪代码,这个是怎么赋值的

进入到createNonHAProxy这个里面

继续走

这句话就是拿到代理对象
返回之后

这样namenode就是代理的proxyInfo中的代理对象

初始化完成之后将代理对象放到DFSClient中,并将dfsClient放到FileSystem中,其实FileSystem里面最终要的就是这个客户端的代理对象,实际上就是namenode的代理对象,这样才能进行从namenode中写文件和读文件
用一个图说明一下这个调用过程,一目了然

好了,今天就分享了FileSystem fs = FileSystem.get(conf);
明天继续讲FSDataInputStream input = fs.open(new Path("/jdk-8u161-linux-x64.tar.gz"));
网友评论