HDFS是運行在通用硬件平臺上的可容錯分佈式文件系統。它優化了大文件的流式讀取模式,適用於那些高吞吐並且對延遲性要求相對比較低的場景。它還通過文件“一次寫入,多次讀取”的簡單策略保證了數據的一致性。HDFS亦使用了“塊複製”的概念,讓數據在集羣的節點間進行復制,每個數據塊複製的份數由“複製因子”決定。
HDFS包含三個服務:
A、NameNode:保存着集羣中所有數據塊位置的一個目錄。
B、Secondary NameNode:週期性同步NameNode的塊索引數據。在同步處理中,Secondary NameNode下載NameNode的image文件和editlogs,並對它們做本地歸併,最後再將歸併完的image文件發回給NameNode。Secondary NameNode並不是NameNode的熱備份,當NameNode故障的時候它並不能工作。
C、DataNode:管理着從NameNode分配過來的數據塊。它並不能感知集羣中其他DataNode的存在,只和NameNode進行交互。
一、HDFS的讀寫操作:
public class HdfsWriter extends Configured implements Tool {
/* (non-Javadoc)
* @see org.apache.hadoop.util.Tool#run(java.lang.String[])
*/
@Override
public int run(String[] arg0) throws Exception {
String localInputPath = arg0[0];
Path outputPath = new Path(arg0[1]);
Configuration conf = getConf();
FileSystem fs = FileSystem.get(conf);
OutputStream os = fs.create(outputPath);
InputStream is = new BufferedInputStream(new FileInputStream(localInputPath));
IOUtils.copyBytes(is, os, conf);
return 0;
}
public static void main(String[] args) {
try {
int returnCode = ToolRunner.run(new HdfsWriter(), args);
System.exit(returnCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class HdfsReader extends Configured implements Tool {
/* (non-Javadoc)
* @see org.apache.hadoop.util.Tool#run(java.lang.String[])
*/
@Override
public int run(String[] as) throws Exception {
Path inputPath = new Path(as[0]);
String localOutputPath = as[1];
Configuration conf = getConf();
FileSystem fs = FileSystem.get(conf);
OutputStream os = new BufferedOutputStream(new FileOutputStream(localOutputPath));
InputStream is = fs.open(inputPath);
IOUtils.copyBytes(is, os, conf);
return 0;
}
public static void main(String[] args) throws Exception {
int returnCode = ToolRunner.run(new HdfsReader(), args);
System.exit(returnCode);
}
}
二、讀寫原理:FileSystem是一個抽象類,代表一個通用文件系統。調用FileSystem.get()方法時,會將Hadoop配置中的fs.default.name參數(形式:hdfs://)作爲URI,選擇初始化一個正確的文件系統。create()方法返回JAVA I/O的OutputStream對象,open()方法返回JAVA I/O的InputStream對象。