1.对于某些应用而言,须要特殊的数据结构来存储自己的数据。

对于基于MapReduce的数据处理。将每一个二进制数据的大对象融入自己的文件里并不能实现非常高的可扩展性,针对上述情况,Hadoop开发了一组更高层次的容器SequenceFile。

2. 考虑日志文件。当中每一条日志记录是一行文本。假设想记录二进制类型。纯文本是不合适的。

这样的情况下,Hadoop的SequenceFile类很合适,由于上述提供了二进制键/值对的永久存储的数据结构。当作为日志文件的存储格式时。能够自己选择键。比方由LongWritable类型表示的时间戳,以及值能够是Writable类型,用于表示日志记录的数量。SequenceFile相同为能够作为小文件的容器。而HDFS和
MapReduce是针对大文件进行优化的。所以通过SequenceFile类型将小文件包装起来,能够获得更高效率的存储和处理。

3. SequenceFile类内部有两个比較基本的内部类各自是SequenceFile.Reader和SequenceFile.Writer

      SequenceFile.Reader

      通过createWriter()静态方法能够创建SequenceFile对象。并返SequenceFile.Writer实例。该静态方法有多个重载版本号,但都须要指定待写入的数据流(FSDataOutputStream或FileSystem对象和Path对象)。Configuration对象,以及键和值的类型。

另外可选參数包含压缩类型以及对应的codec,Progressable回调函数用于通知写入的进度,以及在SequenceFile头文件里存储的Metadata实例。

存储在SequenceFile中的键和值对并不一定是Writable类型。随意能够通过Serialization类实现序列化和反序列化的类型均可被使用。一旦拥有SequenceFile.Writer实例,就能够通过append()方法在文件末尾附件键/值对。

SequenceFile.Writer

    创建SequenceFile.Writer能够通过调用本身的构造函数 SequenceFile.Reader(FileSystem fs, Path file, Configuration conf) 来构造实例对象,从头到尾读取顺序文件的过程是创建SequenceFile.Reader实例后重复调用next()方法迭代读取记录的过程。

读取的是哪条记录与你使用的序列化框架相关。

假设使用的是Writable类型,那么通过键和值作为參数的Next()方法能够将数据流中的下一条键值对读入变量中:

     public boolean next(Writable key。Writable val)。假设键值对成功读取。则返回true,假设已读到文件末尾。则返回false。

详细演示样例代码例如以下所看到的:

import
java.io.IOException;

import java.net.URI;

import java.util.Random;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.FileSystem;

import org.apache.hadoop.fs.Path;

import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.io.SequenceFile;

import org.apache.hadoop.io.Text;



public class sequence {

    /**

     * @param args

     */

    public static  FileSystem fs;

    public static final String Output_path="/home/hadoop/test/A.txt";

    public static Random random=new Random();

    private static final String[] DATA={

          "One,two,buckle my shoe",

          "Three,four,shut the door",

          "Five,six,pick up sticks",

          "Seven,eight,lay them straight",

          "Nine,ten,a big fat hen"

         };

    public static Configuration conf=new Configuration();

    public static void write(String pathStr) throws IOException{

        Path path=new Path(pathStr);

        FileSystem fs=FileSystem.get(URI.create(pathStr), conf);

        SequenceFile.Writer writer=SequenceFile.createWriter(fs, conf, path, Text.class, IntWritable.class);

        Text key=new Text();

        IntWritable value=new IntWritable();

        for(int i=0;i<DATA.length;i++){

            key.set(DATA[i]);

            value.set(random.nextInt(10));

            System.out.println(key);

            System.out.println(value);

           

            System.out.println(writer.getLength());

            writer.append(key, value);

           

        }

        writer.close();

    }

    public static void read(String pathStr) throws IOException{

        FileSystem fs=FileSystem.get(URI.create(pathStr), conf);

        SequenceFile.Reader reader=new SequenceFile.Reader(fs, new Path(pathStr), conf);

        Text key=new Text();

        IntWritable value=new IntWritable();

        while(reader.next(key, value)){

            System.out.println(key);

            System.out.println(value);

        }

    }

   

    public static void main(String[] args) throws IOException {

        // TODO Auto-generated method stub

        write(Output_path);

        read(Output_path);

    }   

}

假设须要在mapreduce中进行SequenceFile的读取和写入,则须要到SequcenFileInputFormat和SequenceFileOutputFormat。演示样例代码例如以下所看到的:

1)输出格式为SequenceFileOutputFormat

public class SequenceFileOutputFormatDemo extends Configured implements Tool {

    public static class SequenceFileOutputFormatDemoMapper extends

            Mapper<LongWritable, Text, LongWritable, Text> {

        public void map(LongWritable key, Text value, Context context)

                throws IOException, InterruptedException {

            context.write(key, value);

        }

    }



    public static void main(String[] args) throws Exception {

        int nRet = ToolRunner.run(new Configuration(),

                new SequenceFileOutputFormatDemo(), args);

        System.out.println(nRet);

    }

    @Override

    public int run(String[] args) throws Exception {

        // TODO Auto-generated method stub

        Configuration conf = getConf();

        Job job = new Job(conf, "sequence file output demo ");

        job.setJarByClass(SequenceFileOutputFormatDemo.class);

        FileInputFormat.addInputPaths(job, args[0]);

        HdfsUtil.deleteDir(args[1]);

        job.setMapperClass(SequenceFileOutputFormatDemoMapper.class);

        // 由于没有reducer,所以map的输出为job的最后输出,所以须要把outputkeyclass

        // outputvalueclass设置为与map的输出一致

        job.setOutputKeyClass(LongWritable.class);

        job.setOutputValueClass(Text.class);

        // 假设不希望有reducer。设置为0

        job.setNumReduceTasks(0);

        // 设置输出类

        job.setOutputFormatClass(SequenceFileOutputFormat.class);

        // 设置sequecnfile的格式,对于sequencefile的输出格式,有多种组合方式,

        //从以下的模式中选择一种,并将其余的凝视掉

        // 组合方式1:不压缩模式

        SequenceFileOutputFormat.setOutputCompressionType(job,

                CompressionType.NONE);





        // 组合方式2:record压缩模式,并指定採用的压缩方式 :默认、gzip压缩等

//        SequenceFileOutputFormat.setOutputCompressionType(job,

//                CompressionType.RECORD);

//        SequenceFileOutputFormat.setOutputCompressorClass(job,

//                DefaultCodec.class);





        // 组合方式3:block压缩模式,并指定採用的压缩方式 :默认、gzip压缩等

//        SequenceFileOutputFormat.setOutputCompressionType(job,

//                CompressionType.BLOCK);

//        SequenceFileOutputFormat.setOutputCompressorClass(job,

//                DefaultCodec.class);

        SequenceFileOutputFormat.setOutputPath(job, new Path(args[1]));

        int result = job.waitForCompletion(true) ?

0 : 1;

        return result;

    }

}

2)输入格式为SequcenFileInputFormat 

public class SequenceFileInputFormatDemo extends Configured implements Tool {

    public static class SequenceFileInputFormatDemoMapper extends

            Mapper<LongWritable, Text, Text, NullWritable> {



        public void map(LongWritable key, Text value, Context context)

                throws IOException, InterruptedException {

            System.out.println("key:   " + key.toString() + "  ;  value: "

                    + value.toString());

        }



    }





    public static void main(String[] args) throws Exception {



        int nRet = ToolRunner.run(new Configuration(),

                new SequenceFileInputFormatDemo(), args);

        System.out.println(nRet);

    }





    @Override

    public int run(String[] args) throws Exception { 

        Configuration conf = getConf();

        Job job = new Job(conf, "sequence file input demo");

        job.setJarByClass(SequenceFileInputFormatDemo.class);

        FileInputFormat.addInputPaths(job, args[0]);

        HdfsUtil.deleteDir(args[1]);

        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.setMapperClass(SequenceFileInputFormatDemoMapper.class);

        job.setNumReduceTasks(1);

        job.setOutputKeyClass(Text.class);

        job.setOutputValueClass(NullWritable.class);

        job.setMapOutputKeyClass(Text.class);

        job.setMapOutputValueClass(Text.class);

        job.setInputFormatClass(SequenceFileInputFormat.class);

        int result = job.waitForCompletion(true) ? 0 : 1;

        return result;

    }

}

或者读取的时候也能够如以下的方式进行读取。可是此时输出格式就为普通FileOutputFormat了,输入格式也为普通FileInputFormat了。演示样例代码如以下所看到的 :

public class MapReduceReadFile {



private static SequenceFile.Reader reader = null;

private static Configuration conf = new Configuration();





public static class ReadFileMapper extends

Mapper<LongWritable, Text, LongWritable, Text> {





/* (non-Javadoc)

* @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN, org.apache.hadoop.mapreduce.Mapper.Context)

*/

@Override

public void map(LongWritable key, Text value, Context context) {

key = (LongWritable) ReflectionUtils.newInstance(

reader.getKeyClass(), conf);

value = (Text) ReflectionUtils.newInstance(

reader.getValueClass(), conf);

try {

while (reader.next(key, value)) {

System.out.printf("%s\t%s\n", key, value);

context.write(key, value);

}

} catch (IOException e1) {

e1.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

/**

* @param args

* @throws IOException

* @throws InterruptedException

* @throws ClassNotFoundException

*/

public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {



Job job = new Job(conf,"read seq file");

job.setJarByClass(MapReduceReadFile.class);

job.setMapperClass(ReadFileMapper.class);

job.setMapOutputValueClass(Text.class);

Path path = new Path("logfile2");

FileSystem fs = FileSystem.get(conf);

reader = new SequenceFile.Reader(fs, path, conf);

FileInputFormat.addInputPath(job, path);

FileOutputFormat.setOutputPath(job, new Path("result"));

System.exit(job.waitForCompletion(true)?0:1);

}

}

Hadoop中SequenceFile的使用的更多相关文章

  1. [转] - hadoop中使用lzo的压缩

    在hadoop中使用lzo的压缩算法可以减小数据的大小和数据的磁盘读写时间,不仅如此,lzo是基于block分块的,这样他就允许数据被分解成chunk,并行的被hadoop处理.这样的特点,就可以让l ...

  2. Hadoop之SequenceFile

    Hadoop序列化文件SequenceFile能够用于解决大量小文件(所谓小文件:泛指小于black大小的文件)问题,SequenceFile是Hadoop API提供的一种二进制文件支持.这样的二进 ...

  3. Hadoop基础-SequenceFile的压缩编解码器

    Hadoop基础-SequenceFile的压缩编解码器 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Hadoop压缩简介 1>.文件压缩的好处 第一:较少存储文件占用 ...

  4. hadoop基础-SequenceFile详解

    hadoop基础-SequenceFile详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.SequenceFile简介 1>.什么是SequenceFile 序列文件 ...

  5. Hadoop中Partition深度解析

    本文地址:http://www.cnblogs.com/archimedes/p/hadoop-partitioner.html,转载请注明源地址. 旧版 API 的 Partitioner 解析 P ...

  6. Hadoop中序列化与Writable接口

    学习笔记,整理自<Hadoop权威指南 第3版> 一.序列化 序列化:序列化是将 内存 中的结构化数据 转化为 能在网络上传输 或 磁盘中进行永久保存的二进制流的过程:反序列化:序列化的逆 ...

  7. Hadoop 中利用 mapreduce 读写 mysql 数据

    Hadoop 中利用 mapreduce 读写 mysql 数据   有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 pv.uv 数据,然后为了实时查询的需求,或者一些 OLAP ...

  8. Hadoop中客户端和服务器端的方法调用过程

    1.Java动态代理实例 Java 动态代理一个简单的demo:(用以对比Hadoop中的动态代理) Hello接口: public interface Hello { void sayHello(S ...

  9. Hadoop中WritableComparable 和 comparator

    1.WritableComparable 查看HadoopAPI,如图所示: WritableComparable继承自Writable和java.lang.Comparable接口,是一个Writa ...

随机推荐

  1. Spark常用函数讲解之键值RDD转换

    摘要: RDD:弹性分布式数据集,是一种特殊集合 ‚ 支持多种来源 ‚ 有容错机制 ‚ 可以被缓存 ‚ 支持并行操作,一个RDD代表一个分区里的数据集RDD有两种操作算子:         Trans ...

  2. 地下迷宫(bfs输出路径)

    题解:开一个pre数组用编号代替当前位置,编号用结构题另存,其实也可以i*m+j来代替,我写的有点麻烦了; 代码: #include <iostream> #include <cst ...

  3. jsp当参数为空的时候默认显示值

    当${business.branchName }为空或者不存在的时候显示“请选择门店” <c:out value="${business.branchName }" defa ...

  4. JSTL学习笔记(核心标签)

    一.JSTL标签分类: 核心标签 格式化标签 SQL标签 XML标签 JSTL函数 二.核心标签       引用方式:<%@ taglib prefix="c" uri=& ...

  5. mvc 5 的过滤器和webapi 过滤器 对应实现的action过滤器区别

     asp.net webapi  Action过滤器实现这个: #region 程序集 System.Web.Http, Version=5.2.3.0, Culture=neutral, Publi ...

  6. solr group分组查询

    如:http://localhost:8080/solr/test_core/select?q=*:*&wt=json&indent=true&group=true&g ...

  7. Android-------- AlertDialog中EditText无法弹出输入法的解决

    文章转自:http://21jhf.iteye.com/blog/2007375: 如果AlertDialog中有编辑录入框(newMainLayout里面动态创建了EditText控件),show后 ...

  8. ios属性和成员变量写在.h文件和.m文件中 区别?

    1  其实是一样的.在.m文件上只能.m文件内部的才能访问的这个变量,如果在.h文件中,其他的文件也可以访问到这个变量. 2  写.h文件里边可以和其他的类进行交互,写.m里边只是在本类中使用! 3 ...

  9. java.lang.NoClassDefFoundError: javax/xml/stream/XMLStreamException

    ?缺少jsr173_1.0_api.jar 包 或者jdk版本不对(包括工程和tomcat等服务器的jdk版本) 以前的一个xfire工程,今天重新导进后不能运行,修改工程的jdk版本不行,最后发现是 ...

  10. git add和被ignore的文件

    如果有如下的目录结构: workspace tree | --------------------- |                             | hello.c           ...