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