[HDFS]HDFS优化-小文件合并.md

hdfs优化-小文件合并

一.背景

hdfs的namenode存储元数据,包含fsimage(存储文件的owership和permissions,文件包含哪些blockid),block保存在哪个datanode,这些信息在启动后加载到内存,所以如果小文件特别多,则会对内存造成很大的压力。 解决方法:可以使用小文件合并的方式来解决此问题,优化hdfs的存储。这里的小文件指的是小于blocksize(hadoop2.x为128M)的文件。这里使用的SequenceFile方法来处理。

二.处理代码示例

这里使用的idea进行连接hadoop集群进行测试使用

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();
   }
}

上传小文件之后:

上传小文件之后

读取小文件效果:

输入图片说明

转载于:https://my.oschina.net/u/947726/blog/714776

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值