OutputFormat是MapReduce输出的基类,所有实现MapReduce输出都实现了OutputFormat接口。默认输出格式是TextOutputFormat
当需要输出数据到MySQL/HBase/Elasticsearch等存储框架时需要自定义OutputFormat。
定义OutputFormat步骤:
1.自定义一个类继承FileOutputFormat
2.改写RecordWriter,具体改写输出数据的方法wtite()
实例:
(1)编写LogMapper类
/**
* @author LS
* @date 2021/12/15 8:37
* @description
*/
public class LogMapper extends Mapper<LongWritable,Text,Text,NullWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
context.write(value,NullWritable.get());
}
}
(2)编写LogReducer类
/**
* @author LS
* @date 2021/12/15 8:39
* @description
*/
public class LogReducer extends Reducer<Text,NullWritable,Text,NullWritable> {
@Override
protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
for (NullWritable value : values) {
context.write(key,NullWritable.get());
}
}
}
(3)自定义一个LogOutputFormat类
/**
* @author LS
* @date 2021/12/15 8:52
* @description
*/
public class LogOutputFormat extends FileOutputFormat<Text,NullWritable> {
@Override
public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {
LogRecordWriter logRecordWriter = new LogRecordWriter(job);
return logRecordWriter;
}
}
(4)编写LogRecordWriter类
/**
* @author LS
* @date 2021/12/15 8:42
* @description
*/
public class LogRecordWriter extends RecordWriter<Text,NullWritable> {
private FSDataOutputStream atguiguout;
private FSDataOutputStream otherout;
public LogRecordWriter(TaskAttemptContext job) {
try {
FileSystem fs = FileSystem.get(job.getConfiguration());
atguiguout = fs.create(new Path("F:\\atguigu.log"));
otherout = fs.create(new Path("F:\\other.log"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void write(Text text, NullWritable nullWritable) throws IOException, InterruptedException {
String log = text.toString();
if (log.contains("atguigu")){
atguiguout.writeBytes(log+"\n");
}else{
otherout.writeBytes(log+"\n");
}
}
@Override
public void close(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
IOUtils.closeStreams(otherout);
IOUtils.closeStreams(atguiguout);
}
}
(5)编写LogDriver类
/**
* @author LS
* @date 2021/12/15 8:55
* @description
*/
public class LogDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(LogDriver.class);
job.setMapperClass(LogMapper.class);
job.setReducerClass(LogReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NullWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class);
job.setOutputFormatClass(LogOutputFormat.class);
FileInputFormat.setInputPaths(job,new Path("F:\\inputoutputformat"));
FileOutputFormat.setOutputPath(job,new Path("F:\\of"));
job.waitForCompletion(true);
}
}