mapreduce的自定义输出格式

22 篇文章 0 订阅
8 篇文章 0 订阅

mapreduce自定义输出格式

概念:

  • 当普通的输出格式不能满足客户的要求的时候。因为普通的输出格式是将结果直接输出到一个单一的文件中去。现在有的需求是将处理的结果输出到数据库中,或者是将结果按照不同的需求输出到不同的文件中去。

举例:

  • 现在有一个需求是将一个文件读取进来后,然后判断文件中的被切割的字符串是否含有要求的字符串,如果有的话就输出到对应的文件中去。

源码解析:

  • 源码
public abstract class OutputFormat<K, V> {

  /** 
   * Get the {@link RecordWriter} for the given task.
   *
   * @param context the information about the current task.
   * @return a {@link RecordWriter} to write the output for the job.
   * @throws IOException
   */
  public abstract RecordWriter<K, V> 
    getRecordWriter(TaskAttemptContext context
                    ) throws IOException, InterruptedException;

  /** 
   * Check for validity of the output-specification for the job.
   *  
   * <p>This is to validate the output specification for the job when it is
   * a job is submitted.  Typically checks that it does not already exist,
   * throwing an exception when it already exists, so that output is not
   * overwritten.</p>
   *
   * @param context information about the job
   * @throws IOException when output should not be attempted
   */
  public abstract void checkOutputSpecs(JobContext context
                                        ) throws IOException, 
                                                 InterruptedException;

  /**
   * Get the output committer for this output format. This is responsible
   * for ensuring the output is committed correctly.
   * @param context the task context
   * @return an output committer
   * @throws IOException
   * @throws InterruptedException
   */
  public abstract 
  OutputCommitter getOutputCommitter(TaskAttemptContext context
                                     ) throws IOException, InterruptedException;
}
  • 解说:
    • 这是最基础的OutputFormat类,其中包含了有两个方法我们需要注意,第一个方法就是getRecordWriter()方法,第二个方法是和checkOutputSpecs()方法。
    • getRecordWriter():这个方法是获取这个文件的写入方式,必须要实现。
    • checkOutputSpecs():这个方法是检查要写入的文件是否存在,也必须得实现。

具体操作

创造一个文件:
  • 三个文件
...........
1.txt
my name is ll,my name is aa,my name is bb
...........
书写自定义的文件输出类型
  • 创建新的格式CusFileOutputFormat类
/**
 * @description
 * @author: LuoDeSong 694118297@qq.com
 * @create: 2019-06-19 14:12:37
 **/
public class CusFileOutputFormat extends FileOutputFormat<Text, NullWritable> {
    @Override
    public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {
        return new FileRecordWriter(job);
    }
}
* 说明:因为没有必要自己去书写路径检查等一些必要的过程,所以我们可以直接继承OutputFormat类的实现类FileOutputFormat,他其中已经实现了文件路径的检查等工作。我们需要做的就是重新定义我们写文件的格式就行也就是重新写一个RecordWriter类。为getRecordWriter()做准备。
  • 创建新的RecordWriter类FileRecordWriter:
/**
 * @description
 * @author: LuoDeSong 694118297@qq.com
 * @create: 2019-06-19 14:18:53
 **/
public class FileRecordWriter extends RecordWriter<Text, NullWritable> {
    private Logger logger = Logger.getLogger(FileRecordWriter.class);
    FSDataOutputStream ll = null;
    FSDataOutputStream aa = null;
	FSDataOutputStream bb = null;

    public FileRecordWriter(TaskAttemptContext context) {
        logger.info("***********构造方法启动了吗?");
        //1 获得文件系统
        FileSystem fs = null;
        try {
            //2 创建输出的路径
            Path llPath=new Path("c:/ll.txt");
            Path aaPath=new Path("c:/aa.txt");
            Path bbPath=new Path("c:/bb.txt");

            //3 实例化输出流
            ll=fs.create(llPath);
            aa=fs.create(aaPath);
			bb=fs.create(bbPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void write(Text key, NullWritable value) throws IOException, InterruptedException {
       //判断key中的内容是否包含sunwen
        if(key.toString().contains("ll")) {
            //把key中的内容输出到ll.txt
            ll.write(key.toString().getBytes());
        }else if(key.toString().contains("aa")){
            aa.write(key.toString().getBytes());
        }else {
			bb.write(key.toString().getBytes());
		}
    }

    @Override
    public void close(TaskAttemptContext context) throws IOException, InterruptedException {
        if(ll!=null) {
            ll.close();
        }
        if(aa!=null) {
            aa.close();
        }
		if(bb!=null) {
            bb.close();
        }
    }
}
* 说明:需要继承最根本的文件写入的类RecordWriter,然后重新按照自己的方式来重新其中必须的方法,书写的过程和方式已经在代码中做好了注释。。
  • 编写mapper:
/**
 * @description
 * @author: LuoDeSong 694118297@qq.com
 * @create: 2019-06-19 11:36:06
 **/
public class FilterMapper extends Mapper<LongWritable, Text, Text, NullWritable> {

    private Text k = new Text();

    @Override
    protected void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {
        String line = value.toString();
        k.set(line);
        context.write(k, NullWritable.get());
    }


}
  • 编写reducer:
/**
 * @description
 * @author: LuoDeSong 694118297@qq.com
 * @create: 2019-06-19 11:42:22
 **/
public class FilterReduce extends Reducer<Text, NullWritable, Text, NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<NullWritable> values,
                          Context context) throws IOException, InterruptedException {
        String k = key.toString();

        k = k + "\r\n";
        context.write(new Text(k), NullWritable.get());
    }
}
  • 编写Driver:
public class Driver {

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		
		Configuration conf=new Configuration();
		
		Job job=Job.getInstance(conf);
		
		job.setJarByClass(Driver.class);
		
		job.setMapperClass(FilterMapper.class);
		
		job.setReducerClass(FilterReduce.class);
		
		job.setMapOutputKeyClass(Text.class);
		
		job.setMapOutputValueClass(NullWritable.class);
		
		job.setOutputKeyClass(Text.class);
		
		job.setOutputValueClass(NullWritable.class);
		
		job.setOutputFormatClass(FileOutputFormat.class);
		
		FileInputFormat.setInputPaths(job, new Path(args[0]));
		
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		
	    boolean result=job.waitForCompletion(true);
	    
	    System.exit(result?0:1);
		
	}
}

总结:

  • 更改输出格式是一个必需的点,我们整个过程实际上就是追溯源码,仿照源码得来的,希望你在大数据的路上越走越好。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值