1. Map阶段实现
使用Eclipse开发工具打开之前创建的Maven项目HadoopDemo,并且新创建cn.itcast.mr.dedup包,在该路径下编写自定义Mapper类DedupMapper,主要用于读取数据集文件将TextInputFormat默认组件解析的类似<0,2018-3-1 a >键值对修改为<2018-3-1 a,null>。
2. Reduce阶段实现
根据Map阶段的输出结果形式,同样在cn.itcast.mr.dedup包下,自定义Reducer类DedupReducer,主要用于接受Map阶段传递来的数据,根据Shuffle工作原理,键值key相同的数据就会被合并,因此输出数据就不会出现重复数据了。
3. Driver程序主类实现
编写MapReduce程序运行主类DedupDriver,主要用于设置MapReduce工作任务的相关参数。由于本次演示的数据量较小,为了方便、快速地进行案例演示,本案例采用了本地运行模式,对指定的本地E:\\hadoop-eclipse\\input1目录下的源文件(需要提前准备)实现数据去重,并将结果输入到本地E:\\hadoop-eclipse\\output1目录下。
4. 效果测试
为了保证MapReduce程序正常执行,需要先在本地E:\\hadoop-eclipse\\input1目录下创建文件file1.txt和file2.txt;然后,执行MapReduce程序的程序入口DedupDriver类,正常执行完成后,在指定的E:\\hadoop-eclipse\\output1目录下生成结果文件。
1、DedupMapper.Java
package cn.itcast.mr.dedup;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class DedupMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
private static Text line = new Text();//每行数据
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context)throws IOException, InterruptedException {
line = value;
context.write(line,NullWritable.get());
}
}
2、DedupReducer.java
package cn.itcast.mr.dedup;
import java.io.IOException;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class DedupReducer extends Reducer<Text, NullWritable, Text, NullWritable> {
//重写reduce()方法
@Override
protected void reduce(Text key, Iterable<NullWritable> values, Reducer<Text, NullWritable, Text, NullWritable>.Context context) throws IOException, InterruptedException {
context.write(key,NullWritable.get());
}
}
3、DedupDriver.java
package cn.itcast.mr.dedup;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
public class DedupDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(DedupDriver.class);
job.setMapperClass(DedupMapper.class);
job.setReducerClass(DedupReducer.class);
//设置输出类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class);
//设置输入和输出目录
FileInputFormat.addInputPath(job, new Path("E:\\hadoop-eclipse\\input1"));
FileOutputFormat.setOutputPath(job, new Path("E:\\hadoop-eclipse\\output1"));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}