一、首先根据HDFS的API写一段程序,然后是用Eclipse进行debug 单步跟踪,从而查看源码执行流程:

  1. import java.net.URI;  
  2.   
  3. import org.apache.Hadoop.conf.Configuration;  
  4. import org.apache.hadoop.fs.FSDataInputStream;  
  5. import org.apache.hadoop.fs.FileSystem;  
  6. import org.apache.hadoop.fs.Path;  
  7. import org.apache.hadoop.io.IOUtils;  
  8.   
  9. public class testRead1 {  
  10.     public static void main(String[] args) throws Exception{  
  11.         //String uri = args[0];   
  12.         String uri = "hdfs://localhost:9000/user/mmliu/test01.txt";  
  13.         Configuration conf = new Configuration();  
  14.         FileSystem fs = FileSystem.get(URI.create(uri), conf);  
  15.         FSDataInputStream in = null;  
  16.         try {  
  17.             in = fs.open(new Path(uri));  
  18.             IOUtils.copyBytes(in, System.out, 4096, false);  
  19.             in.seek(0);  
  20.             IOUtils.copyBytes(in, System.out, 4096, false);  
  21.         } finally {  
  22.             IOUtils.closeStream(in);  
  23.         }  
  24.     }  
  25. }  
先给出整体的序列图以便后边分析:

Hadoop HDFS源码学习笔记(四)

1、单步追踪client端的代码:

可以看到一开始当get一个FileSystem类的实例的时候,最终会根据我们提供的uri和conf 创建了一个DistributedFileSystem的实例对象,并完成了初始化的过程,初始化函数主要是完成了RPCNamenode和namenode的创建,而这两个变量都是ClientProtocol类型的,ClientProtocol本质上是一个接口,最终完成的是RPC操作。

  1. private static ClientProtocol createRPCNamenode(InetSocketAddress nameNodeAddr,  
  2.     Configuration conf, UserGroupInformation ugi)   
  3.   throws IOException {  
  4.   return (ClientProtocol)RPC.getProxy(ClientProtocol.class,  
  5.       ClientProtocol.versionID, nameNodeAddr, ugi, conf,  
  6.       NetUtils.getSocketFactory(conf, ClientProtocol.class));  
  7. }  
Open阶段,HDFS调用了DistributedFileSystem的open函数:
  1. public FSDataInputStream open(Path f, int bufferSize) throws IOException {  
  2.     statistics.incrementReadOps(1);  
  3.     return new DFSClient.DFSDataInputStream(  
  4.           dfs.open(getPathName(f), bufferSize, verifyChecksum, statistics));  
  5.   }  

相关阅读: