十四、MapReduce--OutputFormat和RecordWriter抽象类

一、基本原理

​ reduce执行完毕之后,每个reduce都会将KV输出到一个文件中。那么KV输出到文件中时是以什么格式输出的呢?这就涉及到两个抽象类:OutputFormat和RecordWriter。

1、OutputFormat

public abstract class OutputFormat<K, V> {
    public OutputFormat() {
    }

public abstract RecordWriter<K, V> getRecordWriter(TaskAttemptContext var1) throws IOException, InterruptedException;

    public abstract void checkOutputSpecs(JobContext var1) throws IOException, InterruptedException;

    public abstract OutputCommitter getOutputCommitter(TaskAttemptContext var1) throws IOException, InterruptedException;
}

其实主要就是创建RecordWriter对象。

2、RecordWriter

public abstract class RecordWriter<K, V> {
    public RecordWriter() {
    }

    //将KV写入到输出流
    public abstract void write(K var1, V var2) throws IOException, InterruptedException;

    //关闭流
    public abstract void close(TaskAttemptContext var1) throws IOException, InterruptedException;
}

主要就是write方法,将KV写入到文件中。

二、常用的OutputFormat实现类

1、TextOutputFormat

​ 继承 FileOutputFormat,返回的RecordWriter是TextOutputFormat.LineRecordWriter。将每个KV转换为文本的每一行。可以定义key和value在文本中的分隔符,默认是“\t”。

2、SequenceFileOutputFormat

​ 同样继承于FileOutputFormat,返回的RecordWriter是一个匿名内部类,直接将所有的KV以追加的方式写入到文本中,不另外分行(除非原先数据中带有换行)。
​ SequenceFileOutputFormat将它的输出写为一个顺序文件。如果输出需要作为后续 MapReduce任务的输入,这便是一种好的输出格式,因为它的格式紧凑,很容易被压缩。

猜你喜欢

转载自blog.51cto.com/kinglab/2445197