hdfs的namenode存儲元數據,包含fsimage(存儲文件的owership和permissions,文件包含哪些blockid),block保存在哪一個datanode,這些信息在啓動後加載到內存,因此若是小文件特別多,則會對內存形成很大的壓力。 解決方法:可使用小文件合併的方式來解決此問題,優化hdfs的存儲。這裏的小文件指的是小於blocksize(hadoop2.x爲128M)的文件。這裏使用的SequenceFile方法來處理。java
這裏使用的idea進行鏈接hadoop集羣進行測試使用node
package com.boyka.hdfs.smallfiles; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; import org.junit.After; import org.junit.Before; import org.junit.Test; public class HdfsDemon { FileSystem fs; Configuration conf; @Before public void setup() throws IOException { // 默認加載jar配置 core-site.xml hdfs-site.xml拷貝到/src目錄 System.setProperty("HADOOP_USER_NAME","root"); conf = new Configuration(); fs = FileSystem.get(conf); } @After public void close() throws IOException { fs.close(); } /** * 處理小文上傳 * [[@throws](http://my.oschina.net/throws)](http://my.oschina.net/throws) Exception */ [[@Test](http://my.oschina.net/azibug)](http://my.oschina.net/azibug) public void seq() throws Exception { Path path = new Path("/user/seq"); SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, path, Text.class, Text.class);//存儲到hdfs的path路徑 File file = new File("/Users/mac/Documents/needfile/test"); for(File f : file.listFiles()) { writer.append(new Text(f.getName()),new Text(FileUtils.readFileToString(f)));//內容類型爲Text Text } writer.close(); } /** * 查看sequencefile,循環獲取小文件的內容 * [[@throws](http://my.oschina.net/throws)](http://my.oschina.net/throws) IOException */ @Test public void catseq() throws IOException { Path path = new Path("/user/seq"); SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf); Text key = new Text(); Text value = new Text(); while(reader.next(key, value)) { System.out.println(key); System.out.println(value); System.out.println("--------------------"); } reader.close(); } }
上傳小文件以後:apache
讀取小文件效果:app